您的位置:首页 > 编程语言 > C语言/C++

C++标准库 之 ifstream类的使用和介绍 zz

2009-04-13 22:33 357 查看
ifstream继承自istream类,istream类只有一个iostream库中创建好的cin对象,对应一个输入设备就是pc机的键盘,而ifstream类则没有在fstream中有创建好的对象,原因上一篇文章已经说了。

ifstream是文件输入类,输入的源是文件,目标是内存,从文件向内存输入,也就是读取文件的意思了。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

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这个全局函数来获取一行字符,使用如下:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

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: /article/6558545.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: