【发布时间】:2011-09-17 23:51:40
【问题描述】:
谷歌搜索文件输入我发现了两种从文件输入文本的方法 - fopen 和 ifstream。下面是两个sn-ps。我有一个文本文件,其中包含需要读取的整数的一行。我应该使用 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";
}
【问题讨论】: