【C/C++檔案處理系列】fstream::open函式開啟檔案
阿新 • • 發佈:2019-02-02
【fstream::open】
函式原型
void open (const char* filename,
ios_base::openmode mode = ios_base::in | ios_base::out);
其中 filename 為檔名字
openmode 如下:
in input 以讀的方式開啟,即input 記憶體
out output 以寫的方式開啟 , 即output 記憶體,寫入磁碟
binary binary 二進位制模式
ate at end 輸出位置在檔案結尾
app append 追加寫,需要已經存在的檔案
trunc truncate 檔案開啟之前的任何內容都會丟失
###
fstream 中函式模型
/** * @brief Opens an external file. * @param s The name of the file. * @param mode The open mode flags. * @return @c this on success, NULL on failure * * If a file is already open, this function immediately fails. * Otherwise it tries to open the file named @a s using the flags * given in @a mode. **/ __filebuf_type* open(const char* __s, ios_base::openmode __mode); /** * @brief Opens an external file. * @param s The name of the file. * @param mode The open mode flags. * @return @c this on success, NULL on failure */ __filebuf_type* open(const std::string& __s, ios_base::openmode __mode) { return open(__s.c_str(), __mode); }
程式碼實現
#include<fstream>
using namespace std;
int main()
{
fstream fs;
fs.open("myfile.txt",ios::app|ios::in|ios::out);
fs<<"more strings "<<endl;
fs.close();
return 0;
}
多次執行 ,檔案內容累加。
另外 fstream中 與fopen() 引數的比較:如下
/** * * +---------------------------------------------------------+ * | ios_base Flag combination stdio equivalent | * |binary in out trunc app | * +---------------------------------------------------------+ * | + "w" | * | + + "a" | * | + "a" | * | + + "w" | * | + "r" | * | + + "r+" | * | + + + "w+" | * | + + + "a+" | * | + + "a+" | * +---------------------------------------------------------+ * | + + "wb" | * | + + + "ab" | * | + + "ab" | * | + + + "wb" | * | + + "rb" | * | + + + "r+b" | * | + + + + "w+b" | * | + + + + "a+b" | * | + + + "a+b" | * +---------------------------------------------------------+