C++ 读取文本文件 - fopen 与 ifstream
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6399822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading a text file - fopen vs. ifstream
提问by Vinicius Kamakura
Googling file input I found two ways to input text from a file - fopen and ifstream. Below are the two snippets. I have a text file consisting of one line with an integer I need to read in. Should I use fopen or ifstream?
谷歌搜索文件输入我找到了两种从文件输入文本的方法 - fopen 和 ifstream。下面是两个片段。我有一个文本文件,其中一行包含一个我需要读入的整数。我应该使用 fopen 还是 ifstream?
SNIPPET 1 - FOPEN
片段 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);
}
SNIPPET 2 - IFSTREAM
片段 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";
}
采纳答案by Josh Peterson
I would prefer ifstream because it is a bit more modular than fopen. Suppose you want the code that reads from the stream to also read from a string stream, or from any other istream. You could write it like this:
我更喜欢 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;
}
Now you can test stream_reader
without using a real file, or use it to read from other input types. This is much more difficult with fopen.
现在您可以在stream_reader
不使用真实文件的情况下进行测试,或者使用它来读取其他输入类型。这对于 fopen 来说要困难得多。
回答by Vinicius Kamakura
Since this is tagged as C++, I will say ifstream. If it was tagged as C, i'd go with fopen :P
由于这被标记为 C++,我会说 ifstream。如果它被标记为 C,我会选择 fopen :P