[英]How do I read an empty file in C++?
How do I read an empty file in c ++? 如何在C ++中读取一个空文件?
What while loop condition do i use to read the empty file? 我使用什么while循环条件读取空文件?
Because !fin.eof()
condition doesn't work and creates a endless loop. 因为!fin.eof()
条件不起作用并创建了一个无限循环。
I use turbo c++ and I have 2 files. 我使用turbo c ++,我有2个文件。 The music library file already has some albums. 音乐库文件已经有一些专辑。 I need to filter out and remove the repeated albums and add it in the filterfile. 我需要过滤掉并删除重复的相册,然后将其添加到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. 仅当尝试读取文件末尾时才设置eof()
:您必须尝试读取至少一次。 From std::basic_ios::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. 此函数仅报告最新I / O操作设置的流状态,不检查关联的数据源。 For example, if the most recent I/O was a get(), which returned the last byte of a file, eof() returns false. 例如,如果最新的I / O是get(),它返回了文件的最后一个字节,则eof()返回false。 The next get() fails to read anything and sets the eofbit. 下一个get()无法读取任何内容并设置eofbit。 Only then eof() returns true. 只有这样eof()才返回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. 如果使用operator>>
读取不同于std::string
的内容,则错误检查的逻辑将更改-循环可能结束并且尚未设置eof。 (Say if you read in int
s and extraction operation encounters a non-digit along the way). (例如,如果您读入int
并且提取操作在过程中遇到非数字)。 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? 但是,为什么要读取一个空文件?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.