简体   繁体   中英

How do I read an empty file in C++?

How do I read an empty file in c ++?

What while loop condition do i use to read the empty file?

Because !fin.eof() condition doesn't work and creates a endless loop.

I use turbo c++ and I have 2 files. The music library file already has some albums. I need to filter out and remove the repeated albums and add it in the filterfile.

My code is the following:

void albumfilter()
{
    song s;
    album a;

    ifstream fin;
    fstream finout;

    fin.open("Musiclibrary.txt", ios::binary);

    while(!fin.eof())
    {
        fin.read((char*)&s,sizeof(s));
        if(fin.eof())
        break;

        finout.open("Filteralbum.txt", ios::binary| ios::in| ios::out);

        while(!finout.eof())
        {
            finout.read((char*)&a, sizeof(a));

            if(strcmp(a.getfilter_albumname(), s.getalbum())!=0)
            {
                strcpy(a.getfilter_albumname(),s.getalbum());
                 finout.write((char*)&a, sizeof(a));
                finout.close();
            }
        }
    }

    fin.close();
}

Is this code correct?

eof() will only be set when an attempt is made to read past the end of the file: you must attempt to read at least once. From std::basic_ios::eof :

This function only reports the stream state as set by the most recent I/O operation, it does not examine the associated data source. For example, if the most recent I/O was a get(), which returned the last byte of a file, eof() returns false. The next get() fails to read anything and sets the eofbit. Only then eof() returns true.

Just like you would read a non-empty file, you put the read operation as a condition for the loop. The code should be self-explanatory:

std::vector<std::string> lines;
std::ifstream file("file.x");

if (file.is_open()) {

    while (std::getline(file, line)) {  // you can use operator>> here, too
        lines.push_back(line);
    }

    if (file.bad() || file.fail()) {
        std::cout << "An error occured during reading.";
    } else if (lines.empty()) {
        std::cout << "The file is empty.";
    }

} else {
    std::cout << "Couldn't open file.";
}

If you use operator>> to read something different than std::string s, then the logic for error checking changes - it's possible that the loops ends and eof isn't set yet. (Say if you read in int s and extraction operation encounters a non-digit along the way). You need to take this into account.

       ifstream fin("empty-file.txt");
       string line;
       while(true){
            fin>>line;
            if(fin.eof())break;
       }

I think this should do. But why do you want to read an empty file?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM