1. 程式人生 > >C++ 檔案的I/O

C++ 檔案的I/O

(出處:C++ Primer Plus  第6版  中文版_  17.4  檔案輸入和輸出)

一,寫入檔案

要讓程式寫入檔案,必須這樣做:

1,建立一個ofstream物件來管理輸入流;

2,將該物件與特定的檔案關聯起來;

3,以使用cout的方式使用該物件,唯一的區別是將進入檔案,而不是螢幕。

要完成以上任務,首先應該包含標頭檔案fstream。對於大多數實現來說,包含該標頭檔案便自動包括iostream檔案。

例:

ofstream fout;

fout.open("xxx.txt");

或者:

ofstream fout("xxx.txt");

然後,以使用cout的方式使用fout.

fout<<"AAAAAAAA";//將“AAAAAAAA”放到檔案中。

二,讀取檔案

讀取檔案的要求與寫入檔案相似:

1,建立一個ifstream物件來管理輸入流;

2,將該物件與特定的檔案管理起來;

3,使用cin的方式使用該物件。

讀檔案類似與寫檔案,首先要包含標頭檔案fstream。然後宣告一個ifstream物件,將它與檔名關聯起來。

例:

ifstream fin;

fin.open("xxx.txt");//開啟xxx.txt檔案

或者:

ifstream fin.open("xxx.txt");

三,示例

#include "stdafx.h" #include <iostream> #include <fstream> #include <string>

int main() {     using namespace std;     string filename("20180921-1.txt");

    ofstream fout(filename.c_str());

    fout << "AAAAAAA";     fout.close();

    ifstream fin(filename.c_str());     char ch;     while (fin.get(ch))     {         cout << ch;     }     cout << "Done\n";     fin.close();     return 0; }

四,結果