我正在读取空格/换行符分隔的数字文件。在尝试了 stringstreams 和 ifstreams 之后,在简单性、可读性或效率方面,对于这个简单的任务,C++ 似乎在 fopen 和 fscanf 上并没有太大的改进。
健壮性如何?因为我检查了 fscanf 返回了我期望的项目数,所以这似乎不是问题。我能想到的唯一好处是 stringstream 为您提供了更多选项来处理故障。
下面是一个使用 fscanf 的简单示例:
FILE * pFile;
pFile = fopen ("my_file.txt","r");
if( pFile == NULL ) return -1;
double x,y,z;
int items_read;
while( true )
{
items_read = fscanf( pFile, "%lf %lf %lf", x, y, z );
if( items_read < 3 ) break; // Checks for EOF (which is -1) or reading 1-2 numbers
std::cout << x << " " << y << " " << z << "\n";
}
注意:为了额外的安全性,可以在 Visual Studio 中将 fopen/fscanf 替换为 fopen_s/fscanf_s。