c++ - 如何在 C++ 中读取一个空文件?

标签 c++ file-io

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

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

因为 !fin.eof() 条件不起作用并创建无限循环。

我使用 Turbo C++,我有 2 个文件。音乐库文件中已有一些专辑。我需要过滤掉重复的专辑并将其添加到过滤器文件中。

我的代码如下:

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();
}

这段代码是否正确?

最佳答案

eof() 仅在尝试读取超过文件末尾时才会设置:您必须至少尝试读取一次。来自 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.

关于c++ - 如何在 C++ 中读取一个空文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12264703/

相关文章:

c++ - 创建一个继承自另一个类的类?

postgresql - 我应该如何打开 PostgreSQL 转储文件并向其中添加实际数据?

unix - 文件创建/打开对 st_mtime 和 st_atime 的影响

java - 是否可以在浏览器中编辑计算机上的文件?

c++ - 如何将一个空 vector 提升为一个默认元素的 vector ?

C++构造函数问题

java - openAssetFileDescriptor 不会截断 OneDrive 文件

c++ - 用c++写一个循环文件

c++ - Windows 上的 strptime() 等价物?

c++ - 如何在 Visual Studio 2008 中创建自定义清理(清理后)事件?