如何在C++中读取空文件?

0 c++ file-io

如何在c ++中读取空文件?

我用什么循环条件来读取空文件?

因为!fin.eof()条件不起作用并产生无限循环.

我使用turbo c ++,我有2个文件.音乐库文件已有一些专辑.我需要过滤掉并删除重复的相册并将其添加到filterfile中.

我的代码如下:

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();
}
Run Code Online (Sandbox Code Playgroud)

这段代码是否正确?

hmj*_*mjd 7

eof()只有在尝试读取文件末尾时才会设置:您必须尝试至少读取一次.来自std::basic_ios::eof:

此函数仅报告由最近的I/O操作设置的流状态,它不检查关联的数据源.例如,如果最近的I/O是get(),它返回文件的最后一个字节,则eof()返回false.下一个get()无法读取任何内容并设置eofbit.只有这样eof()才会返回true.


jro*_*rok 5

就像您将读取非空文件一样,您将读取操作作为循环的条件.代码应该是不言自明的:

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.";
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的operator>>是读取与std::strings 不同的内容,则错误检查的逻辑会发生变化 - 循环可能会结束,而eof尚未设置.(假如你读入ints并且提取操作在整个过程中遇到非数字).你需要考虑到这一点.