C++檔案讀寫操作

來源:互聯網
上載者:User

標籤:pen   字串   test   ace   定義   using   lin   ++   檔案開啟   

讀寫操作流程:

  1.為要進行操作的檔案定義一個流對象。

  2.開啟(建立)檔案。

  3.進行讀寫操作。

  4.關閉檔案。

詳解:

  1.建立流對象:

    輸入檔案流類(執行讀操作):ifstream  in;

    輸出檔案流類(執行寫操作):ofstream  out;

    輸入輸出檔案流類:fstream both;

  注意:這三類檔案流類都定義在fstream中,所以只要在標頭檔中加上fstream即可。

 

  2.使用成員函數open開啟函數:

    使用方式:       ios::in                       以輸入方式開啟檔案(讀操作)

                ios::out        以輸出方式開啟檔案(寫操作),如果已經存在此名字的檔案夾,則將其原有內容全部清除

                ios::app                    以輸入方式開啟檔案,寫入的資料增加至檔案末尾

                ios::ate                     開啟一個檔案,把檔案指標移到檔案末尾

                  ios::binary                 以二進位方式開啟一個檔案,預設為文本開啟檔案

    舉例:定義流類對象:ofstream out   (輸出資料流)

          進行寫操作:out.open("test.dat", ios::out);            //開啟一個名為test.dat的問件

 

  3.文字檔的讀寫:

    (1)把字串 Hello World 寫入到磁碟檔案test.dat中

      

#include<iostream>#include<fstream>using namespace std;int main(){  ofstream fout("test.dat", ios::out);  if(!fout)  {       cout<<"檔案開啟失敗!"<<endl;       exit(1);  }   fout<<"Hello World";  fout.close();  return 0;  }                            檢查檔案test.dat會發現該檔案的內容為 Hello World

    

    (2)把test.dat中的檔案讀出來並顯示在螢幕上

#include<iostream>#include<fstream>using namespace std;int main(){  ifstream fin("test.dat", ios::in);  if(!fin)  {       cout<<"檔案開啟失敗!"<<endl;       exit(1);  }   char str[50];  fin.getline(str, 50)  cout<<str<<endl;  fin.close();  return 0;  }                           

  4.檔案的關閉:

    流對象.close();   //沒有參數

 

C++檔案讀寫操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.