看不懂这段代码?这是关于在 C++ 中读取文件

Don't understand this piece of code ? It's about reading a file in c++

我有一项用 C++ 做的工作,我想读取一个 .txt 文件并使用其中的信息。但是我们的老师给了我们开头的代码来帮助我,我真的不明白。我是 c++ 的初学者,所以我一直在寻找它几个小时,但我没有找到答案,谢谢!

这是一段代码:

int main(int argc, const char** argv)
{
    std::ifstream* myfile = NULL;

    if (argc == 2) {
        file = myfile = new std::ifstream(argv[1]);
        if (myfile->fail())
            std::cerr << "Error at the opening of the file'" << argv[1] << "'" << std::endl;
    }
    else
        std::cerr << "No file name." << std::endl;

    while (*file) {
        std::string event;
        *file >> event;
        if (!(*file)) break;

        if (event == "recipe") {
            std::string namerecipe;
            *file >> recipe;

...

所以我不明白?什么是 * 文件?和文件?它是文件上的指针吗?为什么没有像 get line 这样的功能在上面工作?为什么 "while *file" 应该这样做? 非常感谢你 !

  1. *file 是指向输入文件流 ifstream 对象的指针。
  2. file 是您的输入文件流 ifstream 对象。

  3. while(*file) 正在使用流的布尔运算符来测试输入文件流中的错误情况(在读取文件时没有错误)

int main(int argc, const char** argv)
{

一个典型的函数入口点。

    std::ifstream* myfile = NULL;

    if (argc == 2) {

确保有足够的参数从 argv[1] 获取文件名。

        file = myfile = new std::ifstream(argv[1]);

动态分配文件输入流并尝试使用它打开 argv[1] 中指定的文件。然后将该文件流分配给两个指针,filemyfile。我承认没有看到有两个指针的意义,但我也没有首先看到指针的意义。

        if (myfile->fail())

调用流的 fail 函数。这将测试流是否有任何问题。此时所有要测试的是流是否打开。

            std::cerr << "Error at the opening of the file'" << argv[1] << "'" << std::endl;
    }
    else
        std::cerr << "No file name." << std::endl;

    while (*file) {

取消引用 file 指针以对文件对象进行操作。这将具有调用流的布尔运算符的效果。这与调用 !file->fail() 具有相同的(C++11 或更新的)或如此相似以致于在这种情况下(C++11 之前)效果无关紧要。更多关于 operator bool 的信息:http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool

        std::string event;
        *file >> event;

从流中读取一个以空格分隔的标记,一个单词。

        if (!(*file)) break;

运算符再次布尔。失败时退出循环。

        if (event == "recipe") {
            std::string namerecipe;
            *file >> recipe;

从流中读取另一个词。

代码可以按以下方式重写:

int main(int argc, const char** argv)
{
    if (argc == 2) 
    {
        std::ifstream myfile(argv[1]);
        if (myfile)
        {
            std::string event;
            while (myfile >> event) 
            {
                //this function is getting deep. Consider spinning this off into a new function
                if (event == "recipe") 
                {
                    std::string namerecipe;
                    if (myfile >> recipe)
                    {
                        // do stuff that is missing from code sample
                    }
                    else
                    {
                        // handle error
                     }
                 }
            }
        }
        else
        {
            std::cerr << "Error at the opening of the file'" << argv[1] << "'" << std::endl;
        }
    }
    else
    {
        std::cerr << "No file name." << std::endl;
    }
}