c++文件流基本用法(fstream, ifstream, ostream)


原文鏈接

前言:
c++的文件流處理其實很簡單,前提是你能夠理解它。文件流本質是利用了一個buffer中間層。有點類似標准輸出和標准輸入一樣。

c++ IO的設計保證IO效率,同時又兼顧封裝性和易用性。本文將會講述c++文件流的用法。

有錯誤和疏漏的地方,歡迎批評指證。

需要包含的頭文件: <fstream> 

名字空間: std

也可以試用<fstream.h>

fstream提供了三個類,用來實現c++對文件的操作。(文件的創建,讀寫)。
ifstream -- 從已有的文件讀

ofstream -- 向文件寫內容

fstream - 打開文件供讀寫

支持的文件類型

實際上,文件類型可以分為兩種: 文本文件和二進制文件.

文本文件保存的是可讀的字符, 而二進制文件保存的只是二進制數據。利用二進制模式,你可以操作圖像等文件。用文本模式,你只能讀寫文本文件。否則會報錯。

 

例一: 寫文件

聲明一個ostream變量

  1. 調用open方法,使其與一個文件關聯
  2. 寫文件
  3. 調用close方法.
  1. #include <fstream.h>
  2.  
  3. void main
  4. {
  5. ofstream file;
  6.  
  7. file. open ( "file.txt" );
  8.  
  9. file<< "Hello file/n"<< 75;
  10.  
  11. file. close ( );
  12. }

可以像試用cout一樣試用操作符<<向文件寫內容.
Usages:

  1.  
  2. file<< "string/n";
  3. file. put ( 'c' );

例二:  讀文件

1. 聲明一個ifstream變量.

2. 打開文件.

3. 從文件讀數據

4. 關閉文件.

  1. #include <fstream.h>
  2.  
  3. void main
  4. {
  5. ifstream file;
  6. char output [ 100 ];
  7. int x;
  8.  
  9. file. open ( "file.txt" );
  10.  
  11. file>>output;
  12. cout<<output;
  13. file>>x;
  14. cout<<x;
  15.  
  16. file. close ( );
  17. }
     
    同樣的,你也可以像cin一樣使用>>來操作文件。或者是調用成員函數
    Usages:
  1.  
  2. file>>char *;
  3. file>>char;
  4. file. get ( char );
  5. file. get ( char *, int );
  6. file. getline ( char *, int sz );
  7. file. getline ( char *, int sz, char eol );

1.同樣的,你也可以使用構造函數開打開一個文件、你只要把文件名作為構造函數的

第一個參數就可以了。

  1. ofstream file ( "fl.txt" );
  2. ifstream file ( "fl.txt" );

上面所講的ofstream和ifstream只能進行讀或是寫,而fstream則同時提供讀寫的功能。
void main()

  1. {
  2. fstream file;
  3.  
  4. file. open ( "file.ext",iso:: in|ios:: out )
  5.  
  6. //do an input or output here
  7.  
  8. file. close ( );
  9. }

open函數的參數定義了文件的打開模式。總共有如下模式

  1. 屬性列表
  2.  
  3. ios:: in
  4. ios:: out
  5. ios:: app 從文件末尾開始寫
  6. ios:: binary 二進制模式
  7. ios:: nocreate 打開一個文件時,如果文件不存在,不創建文件。
  8. ios:: noreplace 打開一個文件時,如果文件不存在,創建該文件
  9. ios:: trunc 打開一個文件,然后清空內容
  10. ios:: ate 打開一個文件時,將位置移動到文件尾


Notes

  • 默認模式是文本
  • 默認如果文件不存在,那么創建一個新的
  • 多種模式可以混合,用|(按位或)
  • 文件的byte索引從0開始。(就像數組一樣)

我們也可以調用read函數和write函數來讀寫文件。

 

文件指針位置在c++中的用法:

  1. ios:: beg 文件頭
  2. ios:: end 文件尾
  3. ios:: cur 當前位置
    例子:
  1. file. seekg ( 0,ios:: end );
  2.  
  3. int fl_sz = file. tellg ( );
  4.  
  5. file. seekg ( 0,ios:: beg );

常用的錯誤判斷方法:

  1. good ( ) 如果文件打開成功
  2. bad ( ) 打開文件時發生錯誤
  3. eof ( ) 到達文件尾
    例子:
  1. char ch;
  2. ifstream file ( "kool.cpp",ios:: in|ios:: out );
  3.  
  4. if ( file. good ( ) ) cout<< "The file has been opened without problems;
  5. else cout<<"An Error has happend on opening the file;
  6.  
  7. while (! file. eof ( ) )
  8. {
  9. file>>ch;
  10. cout<<ch;
  11. }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM