ifstream();
ofstream();
ifstream(const char* filename, ios::openmode mode = ios::in)
ofstream(const char* filename, ios::openmode mode = ios::out)
ffstream(const char* filename, ios::openmode mode = ios::in | ios::out)
ifstream(const strings filename, ios::openmode mode = ios::in)
ofstream(const strings filename, ios::openmode mode = ios::out)
ffstream(const strings filename, ios::openmode mode = ios::in | ios::out)
void open (const char* filename, ios::openmode mode = ios::in | ios::out)
void open(const strings filename, ios::openmode mode = ios::in | ios::out)
void close ();
開啟的檔案使用作業系統中的資源,所以一旦使用完,關閉檔案就非常重要。另外,程式寫入檔案流物件的資料通常會在作業系統中緩衝,而不會立即寫入磁碟。關閉檔案時,作業系統將這些資料寫入磁碟,這個過程稱為沖刷緩衝區。關閉檔案將確保緩衝資料不會在電源故障或其他導致程式異常終止的情況下丟失。>>
和插入運算子 <<
在 fstream 物件上讀寫資料。//This program demonstrates reading and writing //a file through an fstream object #include <iostream> #include <fstream> #include <string> using namespace std; int main() { fstream inOutFile; string word; // Used to read a word from the file // Open the file inOutFile.open ("inout.txt"); if (!inOutFile) { cout << "The file was not found." << endl; return 1; } // Read and print every word already in the file while (inOutFile >> word) { cout << word << endl; } // Clear end of file flag to allow additional file operations inOutFile.clear (); // Write a word to the file and close the file inOutFile << "Hello" << endl; inOutFile.close (); return 0; }程式輸出結果:
Hello
Hello
Hello