前言:
c++的文件流處理其實很簡單,前提是你能夠理解它。文件流本質是利用了一個buffer中間層。有點類似標准輸出和標准輸入一樣。
c++ IO的設計保證IO效率,同時又兼顧封裝性和易用性。本文將會講述c++文件流的用法。
有錯誤和疏漏的地方,歡迎批評指證。
需要包含的頭文件: <fstream>
名字空間: std
也可以試用<fstream.h>
fstream提供了三個類,用來實現c++對文件的操作。(文件的創建,讀寫)。
ifstream -- 從已有的文件讀
ofstream -- 向文件寫內容
fstream - 打開文件供讀寫
支持的文件類型
實際上,文件類型可以分為兩種: 文本文件和二進制文件.
文本文件保存的是可讀的字符, 而二進制文件保存的只是二進制數據。利用二進制模式,你可以操作圖像等文件。用文本模式,你只能讀寫文本文件。否則會報錯。
例一: 寫文件
聲明一個ostream變量
- 調用open方法,使其與一個文件關聯
- 寫文件
- 調用close方法.
-
#include <fstream.h>
-
-
void main
-
{
-
ofstream file;
-
-
file. open ( "file.txt" );
-
-
file<< "Hello file/n"<< 75;
-
-
file. close ( );
-
}
可以像試用cout一樣試用操作符<<向文件寫內容.
Usages:
-
-
file<< "string/n";
-
file. put ( 'c' );
例二: 讀文件
1. 聲明一個ifstream變量.
2. 打開文件.
3. 從文件讀數據
4. 關閉文件.
-
#include <fstream.h>
-
-
void main
-
{
-
ifstream file;
-
char output [ 100 ];
-
int x;
-
-
file. open ( "file.txt" );
-
-
file>>output;
-
cout<<output;
-
file>>x;
-
cout<<x;
-
-
file. close ( );
-
}同樣的,你也可以像cin一樣使用>>來操作文件。或者是調用成員函數Usages:
-
-
file>>char *;
-
file>>char;
-
file. get ( char );
-
file. get ( char *, int );
-
file. getline ( char *, int sz );
-
file. getline ( char *, int sz, char eol );
1.同樣的,你也可以使用構造函數開打開一個文件、你只要把文件名作為構造函數的
第一個參數就可以了。
-
ofstream file ( "fl.txt" );
-
ifstream file ( "fl.txt" );
上面所講的ofstream和ifstream只能進行讀或是寫,而fstream則同時提供讀寫的功能。
void main()
-
{
-
fstream file;
-
-
file. open ( "file.ext",iso:: in|ios:: out )
-
-
//do an input or output here
-
-
file. close ( );
-
}
open函數的參數定義了文件的打開模式。總共有如下模式
-
屬性列表
-
-
ios:: in 讀
-
ios:: out 寫
-
ios:: app 從文件末尾開始寫
-
ios:: binary 二進制模式
-
ios:: nocreate 打開一個文件時,如果文件不存在,不創建文件。
-
ios:: noreplace 打開一個文件時,如果文件不存在,創建該文件
-
ios:: trunc 打開一個文件,然后清空內容
-
ios:: ate 打開一個文件時,將位置移動到文件尾
Notes
- 默認模式是文本
- 默認如果文件不存在,那么創建一個新的
- 多種模式可以混合,用|(按位或)
- 文件的byte索引從0開始。(就像數組一樣)
我們也可以調用read函數和write函數來讀寫文件。
文件指針位置在c++中的用法:
-
ios:: beg 文件頭
-
ios:: end 文件尾
-
ios:: cur 當前位置例子:
-
file. seekg ( 0,ios:: end );
-
-
int fl_sz = file. tellg ( );
-
-
file. seekg ( 0,ios:: beg );
常用的錯誤判斷方法:
-
good ( ) 如果文件打開成功
-
bad ( ) 打開文件時發生錯誤
-
eof ( ) 到達文件尾例子:
-
char ch;
-
ifstream file ( "kool.cpp",ios:: in|ios:: out );
-
-
if ( file. good ( ) ) cout<< "The file has been opened without problems;
-
else cout<<"An Error has happend on opening the file;
-
-
while (! file. eof ( ) )
-
{
-
file>>ch;
-
cout<<ch;
-
}