fostream创建文件
Flag Function
ios::in Opens an input file. Use this as an open mode for an ofstreamto prevent truncating an existing file.
ios::out Opens an output file. When used for an ofstreamwithout ios::app, ios::ateor ios::in, ios::truncis implied.
ios::app Opens an output file for appending.
ios::ate Opens an existing file (either input or output) and seeks the end.
ios::nocreate Opens a file only if it already exists. (Otherwise it fails.)
ios::noreplace Opens a file only if it does not exist. (Otherwise it fails.)
ios::trunc Opens a file and deletes the old file, if it already exists.
ios::binary Opens a file in binary mode. Default is text mode.
1: #include "require.h"
2: #include <iostream>
3: #include <fstream>
4: using namespace std;
5:
6: int main() {
7: ifstream in("Iofile.cpp");
8: assure(in, "Iofile.cpp");
9: ofstream out("Iofile.out");
10: assure(out, "Iofile.out");
11: out << in.rdbuf(); // Copy file
12: in.close();
13: out.close();
14: // Open for reading and writing:
15: ifstream in2("Iofile.out", ios::in | ios::out);
16: assure(in2, "Iofile.out");
17: ostream out2(in2.rdbuf());//输出流
18: cout << in2.rdbuf(); // Print whole file
19: out2 << "Where does this end up?";//这句话跟在结尾
20: out2.seekp(0, ios::beg);//设置了out2的输出起始位置
21: out2 << "And what about this?";//这句话在开始写入,覆盖了原始数据
22: in2.seekg(0, ios::beg);//从起始位置开始读入数据
23: cout << in2.rdbuf();//写到标准输出
24: } ///:~
这段程序首先打开一个已有的文件,并将所有的数据copy到一个输出文件中去。
然后打开一个文件IOfile.out并打开一个输出流ostream out2设置为in2.rdbuf(),然后首次输出了in2的内容。这里out2可以对in2.rdbuf()中的数据进行写入。
然后分别在输出流中的内容中前边和后边分别插入了一段字符。输出了in2.rdbuf();