ifstream继承自istream类,istream类只有一个iostream库中创建好的cin对象,对应一个输入设备就是pc机的键盘,而ifstream类则没有在fstream中有创建好的对象,原因上一篇文章已经说了。
ifstream是文件输入类,输入的源是文件,目标是内存,从文件向内存输入,也就是读取文件的意思了。
int _tmain(int argc, _TCHAR* argv[])
{
ifstream hFileRead("c://1.txt", ios::in, _SH_DENYRW); // denies read and write
if (!hFileRead)
{
cout << "read fail!" << endl;
exit(1);
}
char ch;
string content;
while (hFileRead.get(ch)) // the get method retuan false on read end
{
content += ch; // string support oprator+=, use overload
cout.put(ch);
}
system("pause"); // other process can't read or write the file
hFileRead.close();
system("pause");
return 0;
}
使用std::getline这个全局函数来获取一行字符,使用如下:
int _tmain(int argc, _TCHAR* argv[])
{
fstream hFile;
hFile.open("c://1.txt", ios::out | ios::in, _SH_DENYWR); //only deny write
string str;
while(std::getline(hFile, str))
cout << str << endl;
hFile.close();
cin.get();
return 0;
}
zz from: http://www.cnblogs.com/coderlee/archive/2008/01/22/1047990.html