文件输入流
创建ifstream对象
使用ifstream类创建ifstream对象,所获取的对象能够像cin
一样使用>>
运算符从所绑定文件中读取数据。
// 创建一个未绑定的文件输入流
ifstream in;
// 绑定文件输入流文件为1.txt
ifstream in("1.txt");
读取文件数据
使用ifstream对象读取文件中的数据:
ifstream in("1.txt");
if(in) { // 检察打开是否成功
string s;
while(in >> s) {
// 将文件中的数据读出并存入s中
in >> s;
// 使用标准输出cout进行输出
cout << s << endl;
}
}
运行效果:
文件输出流
文件流的打开模式
模式 | 含义 |
---|---|
in | 只读模式(ifstream默认模式) |
out | 只写模式(只读模式会抛弃文件已有数据,ofstream默认模式) |
app | append追加,向文件末尾追加数据 |
ate | at the end定位至文件尾 |
binary | 以二进制形式打开文件 |
创建ofstream对象
使用ofstream类创建ofstream对象,所获取的对象能够像cout
一样使用<<
运算符向所绑定文件中写数据。
// 创建一个未绑定的文件输出流
ofstream out;
// 进行绑定以及打开模式指定
out.open("2.txt", ios::out);
// 绑定文件输入流文件为1.txt
// 并指定打开方式为binary和app(使用|连接多个模式)
ofstream out("2.txt", ios::binary | ios::app);
写入文件数据
使用ofstream向文件中写数据:
ofstream out("1.txt");
if(out) { // 检查是否失败
for (int i = 0; i < 999; ++i) {
out << "爱你" << i + 1 << "遍!" << endl;
}
}
// 注意:关闭的是文件而非输出流对象
// 可以通过out.open()重新绑定文件
out.close();
运行结果:
文件输入输出示例
一个小实践:使用ifstream对象读取C盘下的一张图片,并使用ofstream将其存入同代码目录下的"3.png"中。
ifstream in("C:/Users/zhizi/Pictures/pic.png", ios::binary);
ofstream out("3.png", ios::app | ios::binary);
string s;
while(getline(in, s)) {
out << s << endl;
}
运行效果(图片来源网络,侵权联系删除):