谷歌搜索文件输入我发现了两种从文件输入文本的方法 - 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";
}
由于它被标记为 C++,所以我会说 ifstream。如果它被标记为 C,我会选择 fopen :P
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)