读取文本文件-fopen与ifstream [英] Reading a text file - fopen vs. ifstream
本文介绍了读取文本文件-fopen与ifstream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谷歌文件输入我发现了两种从文件输入文本的方法-fopen和ifstream。下面是两个代码片段。我有一个文本文件,其中一行包含需要读入的整数。我应该使用fopen还是ifstream?
代码段1-FOPEN
FILE * pFile = fopen ("myfile.txt" , "r");
char mystring [100];
if (pFile == NULL)
{
perror ("Error opening file");
}
else
{
fgets (mystring , 100 , pFile);
puts (mystring);
fclose (pFile);
}
代码段2-IFSTREAM
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else
{
cout << "Unable to open file";
}
推荐答案
我更喜欢ifstream,因为它比fOpen更模块化一些。假设您希望从流中读取的代码也可以从字符串流或任何其他iStream中读取。你可以这样写:
void file_reader()
{
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (myfile.good())
{
stream_reader(myfile);
}
myfile.close();
}
else
{
cout << "Unable to open file";
}
}
void stream_reader(istream& stream)
{
getline (stream,line);
cout << line << endl;
}
现在,您可以在不使用实际文件的情况下测试stream_reader
,或者使用它从其他输入类型中读取。使用fOpen时,这要困难得多。
这篇关于读取文本文件-fopen与ifstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文