读取文本文件 - 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";
}
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?
SNIPPET 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
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";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为它被标记为 C++,所以我会说 ifstream。如果它被标记为 C,我会选择 fopen :P
Since this is tagged as C++, I will say ifstream. If it was tagged as C, i'd go with fopen :P
我更喜欢 ifstream,因为它比 fopen 更加模块化。假设您希望从流中读取的代码也从字符串流或任何其他 istream 中读取。您可以这样写:
现在您可以在不使用真实文件的情况下测试
stream_reader
,或者使用它从其他输入类型读取。这对于 fopen 来说要困难得多。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:
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.