gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:45:23 25 4
gpt4 key购买 nike

如何在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com