在搜索文件输入时,我找到了两种从文件输入文本的方法 - 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";
}