如何打开文件

How to opening files

本文关键字:文件 何打开      更新时间:2023-10-16

我在打开文件时遇到了一些问题,所以有人能解释一下while循环是如何在这里工作的吗:

#include <fstream>
std::ifstream infile("thefile.txt");
int a,b;
while (file >> a >> b){}

while循环有一个空的主体。因此,它所要做的就是计算表达式file >> a >> b,直到它得到错误的

file>>a>>b从您打开的文件中读取两个整数。如果遇到错误或文件结尾,则为false。

编辑:

但您在打开文件时提到了问题。在这里,你可以检查它是否成功,或者为什么失败:

if (!file) 
   cerr<<"Couldn't open the file:"<< strerror(errno) <<endl;  // or alternatively
                                                              // use the good old perror()
else 
   ...

实际上不清楚您在问什么。如何正确打开文件,或者while (file >> a >> b)在无法正确打开文件时如何工作。

好吧,试着在评论中解释代码:

#include <fstream>
std::ifstream infile("thefile.txt"); // Tries to open the file in the current working 
                                     // directory the program is executed
int a,b;
while (file >> a >> b){} // Will try to read numeric values from file and store them to 
                         // a and b. If the file couldn't be opened, or the parsing 
                         // for numeric values failed, the loop will never be entered or 
                         // immediately end