When using code
while(!feof(file)) { // Чтение из файла } in C or
while(!file.feof()) { // Чтение из файла } in C ++ you get into trouble - an extra line read, for example. Why? How to verify that the end of the file is reached?
When using code
while(!feof(file)) { // Чтение из файла } in C or
while(!file.feof()) { // Чтение из файла } in C ++ you get into trouble - an extra line read, for example. Why? How to verify that the end of the file is reached?
A sign of reaching the end of a file is set only after an unsuccessful attempt to read past its end . Therefore, if there is no check in the body of the loop whether the reading from the file was successful, the last reading will be exactly the unsuccessful reading that will indicate the reached end of the file (and for you it will look like, for example, the last line read again in the buffer for reading).
Better in the header of the while to do the actual reading with the check — for example, in a C program this might look like
while(fread(&data,sizeof(data),1,file)==1) { // Обработка считанных данных } if (feof(file)) // Достигнут конец файла puts("Ошибка чтения: достигнут конец файла"); else if (ferror(file)) { puts("Ошибка чтения файла"); or in C ++ like
for(int n; file >> n; ) { // Обработка считанного значения n } if (file.bad()) std::cout << "Ошибка ввода-вывода при чтении\n"; else if (file.eof()) std::cout << "Достигнут конец файла\n"; else if (file.fail()) std::cout << "Неверный формат данных\n"; Also, in addition to the eof flag , after reading the entire file, the fail flag can also be set, and if we want to set the cursor to the beginning of fin.seekg (0, fin.beg) , we will not read anything, because fail flag not reset. You can reset using fin.clear () . The current state can be displayed with fin.rdstate () :
ifstream fin; fin.open("E://1.txt", ios_base::in); string str; while(getline(fin, str)) { cout<< str<< " " << fin.rdstate() << endl ; } if (fin.bad()) std::cout << "bad" << endl; if (fin.eof()) std::cout << "eof" << endl; if (fin.fail()) std::cout << "bad | fail" << endl; fin.clear(); fin.seekg(0, fin.beg); if (fin.bad()) std::cout << "bad" << endl; if (fin.eof()) std::cout << "eof" << endl; if (fin.fail()) std::cout << "bad | fail" << endl; while(getline(fin, str)) { cout<<str<< " " << fin.rdstate() << endl ; } Source: https://ru.stackoverflow.com/questions/931673/
All Articles