在看C++編程思想中,每個練習(xí)基本都是使用ofstream,ifstream,fstream,以前粗略知道其用法和含義,在看了幾位大牛的博文后,進行整理和總結(jié):
這里主要是討論fstream的內(nèi)容:
[java] view plaincopy print?
#include?<fstream>?? ofstream??????????? ifstream??????????? fstream????????????
#include <fstream>
ofstream //文件寫操作 內(nèi)存寫入存儲設(shè)備
ifstream //文件讀操作,存儲設(shè)備讀區(qū)到內(nèi)存中
fstream //讀寫操作,對打開的文件可進行讀寫操作
1.打開文件
在fstream類中,成員函數(shù)open()實現(xiàn)打開文件的操作,從而將數(shù)據(jù)流和文件進行關(guān)聯(lián),通過ofstream,ifstream,fstream對象進行對文件的讀寫操作
函數(shù):open()
[cpp] view plaincopy print?
<span?style="font-family:Times?New?Roman;font-size:16px;" >?? public ?member?function???? void ?open?(?const ?char ?*?filename,??????????????ios_base::openmode?mode?=?ios_base::in?|?ios_base::out?);?? ?? void ?open(const ?wchar_t ?*_Filename,??????????ios_base::openmode?mode=?ios_base::in?|?ios_base::out,?? ????????int ?prot?=?ios_base::_Openprot);?? ?? </span>??
public member functionvoid open ( const char * filename,ios_base::openmode mode = ios_base::in | ios_base::out );void open(const wchar_t *_Filename,ios_base::openmode mode= ios_base::in | ios_base::out,int prot = ios_base::_Openprot); 參數(shù): filename?? 操作文件名
?????????? mode??????? 打開文件的方式
?????????? prot???????? 打開文件的屬性??????????????????????????? //基本很少用到,在查看資料時,發(fā)現(xiàn)有兩種方式
打開文件的方式在iOS類(所以流式I/O的基類)中定義,有如下幾種方式:
ios::in 為輸入(讀)而打開文件 ios::out 為輸出(寫)而打開文件 ios::ate 初始位置:文件尾 ios::app 所有輸出附加在文件末尾 ios::trunc 如果文件已存在則先刪除該文件 ios::binary 二進制方式
這些方式是能夠進行組合使用的,以“或”運算(“|”)的方式:例如
[cpp] view plaincopy print?
ofstream?out;?? out.open("Hello.txt" ,?ios::in|ios::out|ios::binary)???????????????????
ofstream out;
out.open("Hello.txt", ios::in|ios::out|ios::binary) //根據(jù)自己需要進行適當?shù)倪x取打開文件的屬性同樣在ios類中也有定義:
0 普通文件,打開操作 1 只讀文件 2 隱含文件 4 系統(tǒng)文件
對于文件的屬性也可以使用“或”運算和“+”進行組合使用,這里就不做說明了。
很多程序中,可能會碰到ofstream out("Hello.txt"), ifstream in("..."),fstream foi("...")這樣的的使用,并沒有顯式的去調(diào)用open()函數(shù)就進行文件的操作,直接調(diào)用了其默認的打開方式,因為在stream類的構(gòu)造函數(shù)中調(diào)用了open()函數(shù),并擁有同樣的構(gòu)造函數(shù),所以在這里可以直接使用流對象進行文件的操作,默認方式如下:
[cpp] view plaincopy print?
<span?style="font-family:Times?New?Roman;font-size:16px;" >?? ofstream?out("..." ,?ios::out);?? ifstream?in("..." ,?ios::in);?? fstream?foi("..." ,?ios::in|ios::out);?? ?? </span>??
ofstream out("...", ios::out);
ifstream in("...", ios::in);
fstream foi("...", ios::in|ios::out); 當使用默認方式進行對文件的操作時,你可以使用成員函數(shù)is_open()對文件是否打開進行驗證
2.關(guān)閉文件
當文件讀寫操作完成之后,我們必須將文件關(guān)閉以使文件重新變?yōu)榭稍L問的。成員函數(shù)close(),它負責(zé)將緩存中的數(shù)據(jù)排放出來并關(guān)閉文件。 這個函數(shù)一旦被調(diào)用,原先的流對象就可以被用來打開其它的文件了,這個文件也就可以重新被其它的進程所訪問了。為防止流對象被銷毀時還聯(lián)系著打開的文件,析構(gòu)函數(shù)將會自動調(diào)用關(guān)閉函數(shù)close。
3.文本文件的讀寫
類ofstream, ifstream 和fstream 是分別從ostream, istream 和iostream 中引申而來的。這就是為什么 fstream 的對象可以使用其父類的成員來訪問數(shù)據(jù)。
一般來說,我們將使用這些類與同控制臺(console)交互同樣的成員函數(shù)(cin 和 cout)來進行輸入輸出。如下面的例題所示,我們使用重載的插入操作符<<:
[cpp] view plaincopy print?
???? ?#include?<fiostream.h> ???int ?main?()?{?? ?????ofstream?out("out.txt" );?? ?????if ?(out.is_open())??? ????{?? ?????????out?<<?"This?is?a?line.\n" ;?? ?????????out?<<?"This?is?another?line.\n" ;?? ?????????out.close();?? ?????}?? ?????return ?0;?? ?}?? ?? This?is?a?line.?? This?is?another?line???
// writing on a text file#include <fiostream.h>int main () {ofstream out("out.txt");if (out.is_open()) {out << "This is a line.\n";out << "This is another line.\n";out.close();}return 0;}//結(jié)果: 在out.txt中寫入:This is a line.This is another line
從文件中讀入數(shù)據(jù)也可以用與 cin>>的使用同樣的方法:
[cpp] view plaincopy print?
?? ???#include?<iostream.h> ?????#include?<fstream.h> ?????#include?<stdlib.h> ??????? ???int ?main?()?{?? ???????char ?buffer[256];?? ???????ifstream?in("test.txt" );?? ???????if ?(!?in.is_open())?? ???????{?cout?<<?"Error?opening?file" ;?exit?(1);?}?? ???????while ?(!in.eof()?)?? ???????{?? ???????????in.getline?(buffer,100);?? ???????????cout?<<?buffer?<<?endl;?? ???????}?? ???????return ?0;?? ???}?? ????? ????This?is?a?line.?? ????This?is?another?line??
// reading a text file#include <iostream.h>#include <fstream.h>#include <stdlib.h>int main () {char buffer[256];ifstream in("test.txt");if (! in.is_open()){ cout << "Error opening file"; exit (1); }while (!in.eof() ){in.getline (buffer,100);cout << buffer << endl;}return 0;}//結(jié)果 在屏幕上輸出This is a line.This is another line
上面的例子讀入一個文本文件的內(nèi)容,然后將它打印到屏幕上。注意我們使用了一個新的成員函數(shù)叫做eof ,它是ifstream 從類 ios 中繼承過來的,當?shù)竭_文件末尾時返回true 。
狀態(tài)標志符的驗證(Verification of state flags)
除了eof()以外,還有一些驗證流的狀態(tài)的成員函數(shù)(所有都返回bool型返回值):
bad() 如果在讀寫過程中出錯,返回 true 。例如:當我們要對一個不是打開為寫狀態(tài)的文件進行寫入時,或者我們要寫入的設(shè)備沒有剩余空間的時候。
fail() 除了與bad() 同樣的情況下會返回 true 以外,加上格式錯誤時也返回true ,例如當想要讀入一個整數(shù),而獲得了一個字母的時候。
eof() 如果讀文件到達文件末尾,返回true。
good() 這是最通用的:如果調(diào)用以上任何一個函數(shù)返回true 的話,此函數(shù)返回 false 。
要想重置以上成員函數(shù)所檢查的狀態(tài)標志,你可以使用成員函數(shù)clear(),沒有參數(shù)。
獲得和設(shè)置流指針(get and put stream pointers)
所有輸入/輸出流對象(i/o streams objects)都有至少一個流指針:
ifstream, 類似istream, 有一個被稱為get pointer的指針,指向下一個將被讀取的元素。 ofstream, 類似 ostream, 有一個指針 put pointer ,指向?qū)懭胂乱粋€元素的位置。 fstream, 類似 iostream, 同時繼承了get 和 put
我們可以通過使用以下成員函數(shù)來讀出或配置這些指向流中讀寫位置的流指針:
tellg() 和 tellp() 這兩個成員函數(shù)不用傳入?yún)?shù),返回pos_type 類型的值(根據(jù)ANSI-C++ 標準) ,就是一個整數(shù),代表當前get 流指針的位置 (用tellg) 或 put 流指針的位置(用tellp).
seekg() 和seekp() 這對函數(shù)分別用來改變流指針get 和put的位置。兩個函數(shù)都被重載為兩種不同的原型:
seekg ( pos_type position ); seekp ( pos_type position ); 使用這個原型,流指針被改變?yōu)橹赶驈奈募_始計算的一個絕對位置。要求傳入的參數(shù)類型與函數(shù) tellg 和tellp 的返回值類型相同。
seekg ( off_type offset, seekdir direction ); seekp ( off_type offset, seekdir direction ); 使用這個原型可以指定由參數(shù)direction決定的一個具體的指針開始計算的一個位移(offset)。它可以是:
ios::beg 從流開始位置計算的位移 ios::cur 從流指針當前位置開始計算的位移 ios::end 從流末尾處開始計算的位移
流指針 get 和 put 的值對文本文件(text file)和二進制文件(binary file)的計算方法都是不同的,因為文本模式的文件中某些特殊字符可能被修改。由于這個原因,建議對以文本文件模式打開的文件總是使用seekg 和 seekp的第一種原型,而且不要對tellg 或 tellp 的返回值進行修改。對二進制文件,你可以任意使用這些函數(shù),應(yīng)該不會有任何意外的行為產(chǎn)生。
以下例子使用這些函數(shù)來獲得一個二進制文件的大小:
[cpp] view plaincopy print?
?? ???#include?<iostream.h> ?????#include?<fstream.h> ??????? ???const ?char ?*?filename?=?"test.txt" ;?? ????? ???int ?main?()?{?? ???????long ?l,m;?? ???????ifstream?in(filename,?ios::in|ios::binary);?? ???????l?=?in.tellg();?? ???????in.seekg?(0,?ios::end);?? ???????m?=?in.tellg();?? ???????in.close();?? ???????cout?<<?"size?of?" ?<<?filename;?? ???????cout?<<?"?is?" ?<<?(m-l)?<<?"?bytes.\n" ;?? ???????return ?0;?? ???}?? ???? ???? ??size?of?example.txt?is?40?bytes.??
// obtaining file size#include <iostream.h>#include <fstream.h>const char * filename = "test.txt";int main () {long l,m;ifstream in(filename, ios::in|ios::binary);l = in.tellg();in.seekg (0, ios::end);m = in.tellg();in.close();cout << "size of " << filename;cout << " is " << (m-l) << " bytes.\n";return 0;}//結(jié)果:size of example.txt is 40 bytes.
4.二進制文件
在二進制文件中,使用<< 和>>,以及函數(shù)(如getline)來操作符輸入和輸出數(shù)據(jù),沒有什么實際意義,雖然它們是符合語法的。
文件流包括兩個為順序讀寫數(shù)據(jù)特殊設(shè)計的成員函數(shù):write 和 read。第一個函數(shù) (write) 是ostream 的一個成員函數(shù),都是被ofstream所繼承。而read 是istream 的一個成員函數(shù),被ifstream 所繼承。類 fstream 的對象同時擁有這兩個函數(shù)。它們的原型是:
write ( char * buffer, streamsize size ); read ( char * buffer, streamsize size );
這里 buffer 是一塊內(nèi)存的地址,用來存儲或讀出數(shù)據(jù)。參數(shù)size 是一個整數(shù)值,表示要從緩存(buffer)中讀出或?qū)懭氲淖址麛?shù)。
[cpp] view plaincopy print?
?? ????#include?<iostream> ??????#include?<fstream.h> ???????? ????const ?char ?*?filename?=?"test.txt" ;?? ?????? ????int ?main?()?{?? ????????char ?*?buffer;?? ????????long ?size;?? ????????ifstream?in?(filename,?ios::in|ios::binary|ios::ate);?? ????????size?=?in.tellg();?? ????????in.seekg?(0,?ios::beg);?? ????????buffer?=?new ?char ?[size];?? ????????in.read?(buffer,?size);?? ????????in.close();?? ?????????? ????????cout?<<?"the?complete?file?is?in?a?buffer" ;?? ?????????? ????????delete []?buffer;?? ????????return ?0;?? ????}?? ?????? ????The?complete?file?is?in?a?buffer??
// reading binary file#include <iostream>#include <fstream.h>const char * filename = "test.txt";int main () {char * buffer;long size;ifstream in (filename, ios::in|ios::binary|ios::ate);size = in.tellg();in.seekg (0, ios::beg);buffer = new char [size];in.read (buffer, size);in.close();cout << "the complete file is in a buffer";delete[] buffer;return 0;}//運行結(jié)果:The complete file is in a buffer
5.緩存和同步(Buffers and Synchronization)
當我們對文件流進行操作的時候,它們與一個streambuf 類型的緩存(buffer)聯(lián)系在一起。這個緩存(buffer)實際是一塊內(nèi)存空間,作為流(stream)和物理文件的媒介。例如,對于一個輸出流, 每次成員函數(shù)put (寫一個單個字符)被調(diào)用,這個字符不是直接被寫入該輸出流所對應(yīng)的物理文件中的,而是首先被插入到該流的緩存(buffer)中。
當緩存被排放出來(flush)時,它里面的所有數(shù)據(jù)或者被寫入物理媒質(zhì)中(如果是一個輸出流的話),或者簡單的被抹掉(如果是一個輸入流的話)。這個過程稱為同步(synchronization),它會在以下任一情況下發(fā)生:
當文件被關(guān)閉時: 在文件被關(guān)閉之前,所有還沒有被完全寫出或讀取的緩存都將被同步。當緩存buffer 滿時: 緩存Buffers 有一定的空間限制。當緩存滿時,它會被自動同步。控制符明確指明: 當遇到流中某些特定的控制符時,同步會發(fā)生。這些控制符包括:flush 和endl。明確調(diào)用函數(shù)sync(): 調(diào)用成員函數(shù)sync() (無參數(shù))可以引發(fā)立即同步。這個函數(shù)返回一個int 值,等于-1 表示流沒有聯(lián)系的緩存或操作失敗。
與50位技術(shù)專家面對面 20年技術(shù)見證,附贈技術(shù)全景圖
總結(jié)
以上是生活随笔 為你收集整理的C++文件读写详解(ofstream,ifstream,fstream) 的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔 推薦給好友。