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();
用fstream在指定文件流模式的情況下也可以自動新建文件:
fstream oo("aa.txt",ofstream::out);
或者
fstream oo("aa.txt",ofstream::app);
都可以
樓主,我試了下,在我電腦上是可以正常運行的。你重新新建個工程試試。。。