1. 程式人生 > >超詳細ofstream和ifstream詳細用法

超詳細ofstream和ifstream詳細用法

ofstream是從記憶體到硬碟,ifstream是從硬碟到記憶體,其實所謂的流緩衝就是記憶體空間(文章最末尾附上了MSDN中關於這兩個函式的解釋);

在C++中,有一個stream這個類,所有的I/O都以這個“流”類為基礎的,包括我們要認識的檔案I/O,stream這個類有兩個重要的運算子:
       1.插入器(<<)   向流輸出資料。比如說系統有一個預設的標準輸出流(cout),一般情況下就是指的顯示器,所以,cout<<"Write Stdout"<<'\n';就表示把字串"Write Stdout"和換行字元('\n')輸出到標準輸出流。
      2. 析取器(>>)   從流中輸入資料。比如說系統有一個預設的標準輸入流(cin),一般情況下就是指的鍵盤,所以,cin>>x;就表示從標準輸入流中讀取一個指定型別(即變數x的型別)的資料。   在C++中,對檔案的操作是通過stream的子類fstream(file stream)來實現的,所以,要用這種方式操作檔案,就必須加入標頭檔案fstream.h。下面就把此類的檔案操作過程一一道來。

一、開啟檔案


  在fstream類中,有一個成員函式open(),就是用來開啟檔案的,其原型是:

void open(constchar* filename,int mode,int access);

引數: filename:  要開啟的檔名
mode:    要開啟檔案的方式
access:   開啟檔案的屬性
開啟檔案的方式在類ios(是所有流式I/O類的基類)中定義,常用的值如下: ios::app:   以追加的方式開啟檔案
ios::ate:   檔案開啟後定位到檔案尾,ios:app就包含有此屬性
ios::binary: 以二進位制方式開啟檔案,預設的方式是文字方式。兩種方式的區別見前文
ios::in:    檔案以輸入方式開啟(檔案資料輸入到記憶體)
ios::out:   檔案以輸出方式開啟(記憶體資料輸出到檔案)
ios::nocreate: 不建立檔案,所以檔案不存在時開啟失敗
ios::noreplace:不覆蓋檔案,所以開啟檔案時如果檔案存在失敗
ios::trunc:  如果檔案存在,把檔案長度設為0
  可以用“或”把以上屬性連線起來,如ios::out|ios::binary   開啟檔案的屬性取值是: 0:普通檔案,開啟訪問
1:只讀檔案
2:隱含檔案
4:系統檔案
  可以用“或”或者“+”把以上屬性連線起來,如3或1|2就是以只讀和隱含屬性開啟檔案。   例如:以二進位制輸入方式開啟檔案c:\config.sys
fstream file1;
file1.open("c:\\config.sys",ios::binary|ios::in,0);
  如果open函式只有檔名一個引數,則是以讀/寫普通檔案開啟,即:
file1.open("c:\\config.sys"); <=> file1.open("c:\\config.sys",ios::in|ios::out,0);   另外,fstream還有和open()一樣的建構函式,對於上例,在定義的時侯就可以開啟檔案了:
fstream file1("c:\\config.sys");   特別提出的是,fstream有兩個子類:ifstream(input file stream)和ofstream(outpu file stream),ifstream預設以輸入方式開啟檔案,而ofstream預設以輸出方式開啟檔案。
ifstream file2("c:\\pdos.def");//以輸入方式開啟檔案
ofstream file3("c:\\x.123");//以輸出方式開啟檔案   所以,在實際應用中,根據需要的不同,選擇不同的類來定義:如果想以輸入方式開啟,就用ifstream來定義;如果想以輸出方式開啟,就用ofstream來定義;如果想以輸入/輸出方式來開啟,就用fstream來定義。

二、關閉檔案

  開啟的檔案使用完成後一定要關閉,fstream提供了成員函式close()來完成此操作,如:file1.close();就把file1相連的檔案關閉。

三、讀寫檔案

  讀寫檔案分為文字檔案和二進位制檔案的讀取,對於文字檔案的讀取比較簡單,用插入器和析取器就可以了;而對於二進位制的讀取就要複雜些,下要就詳細的介紹這兩種方式   1、文字檔案的讀寫
  文字檔案的讀寫很簡單:用插入器(<<)向檔案輸出;用析取器(>>)從檔案輸入。假設file1是以輸入方式開啟,file2以輸出開啟。示例如下:    file2<<"I Love You";//向檔案寫入字串"I Love You"
int i;
file1>>i;//從檔案輸入一個整數值。
  這種方式還有一種簡單的格式化能力,比如可以指定輸出為16進位制等等,具體的格式有以下一些 操縱符 功能 輸入/輸出
dec 格式化為十進位制數值資料 輸入和輸出
endl 輸出一個換行符並重新整理此流 輸出
ends 輸出一個空字元 輸出
hex 格式化為十六進位制數值資料 輸入和輸出
oct 格式化為八進位制數值資料 輸入和輸出
setpxecision(int p) 設定浮點數的精度位數 輸出   比如要把123當作十六進位制輸出:file1<<hex<<123;要把3.1415926以5位精度輸出:file1<<setpxecision(5)<<3.1415926。   2、二進位制檔案的讀寫
①put()
  put()函式向流寫入一個字元,其原型是ofstream &put(char ch),使用也比較簡單,如file1.put('c');就是向流寫一個字元'c'。 ②get()
  get()函式比較靈活,有3種常用的過載形式:   一種就是和put()對應的形式:ifstream &get(char &ch);功能是從流中讀取一個字元,結果儲存在引用ch中,如果到檔案尾,返回空字元。如file2.get(x);表示從檔案中讀取一個字元,並把讀取的字元儲存在x中。   另一種過載形式的原型是: int get();這種形式是從流中返回一個字元,如果到達檔案尾,返回EOF,如x=file2.get();和上例功能是一樣的。   還有一種形式的原型是:ifstream &get(char *buf,int num,char delim='\n');這種形式把字元讀入由 buf 指向的陣列,直到讀入了 num 個字元或遇到了由 delim 指定的字元,如果沒使用 delim 這個引數,將使用預設值換行符'\n'。例如:    file2.get(str1,127,'A');    //從檔案中讀取字元到字串str1,當遇到字元'A'或讀取了127個字元時終止。
③讀寫資料塊
  要讀寫二進位制資料塊,使用成員函式read()和write()成員函式,它們原型如下:      read(unsignedchar *buf,int num);
write(const unsignedchar *buf,int num);
  read()從檔案中讀取 num 個字元到 buf 指向的快取中,如果在還未讀入 num 個字元時就到了檔案尾,可以用成員函式 int gcount();來取得實際讀取的字元數;而 write() 從buf 指向的快取寫 num 個字元到檔案中,值得注意的是快取的型別是 unsigned char *,有時可能需要型別轉換。 例:      unsignedchar str1[]="I Love You";    
int n[5];    
ifstreamin("xxx.xxx");    
ofstreamout("yyy.yyy");    
out.write(str1,strlen(str1));//把字串str1全部寫到yyy.yyy中    
in.read((unsignedchar*)n,sizeof(n));//從xxx.xxx中讀取指定個整數,注意型別轉換    
in.close();out.close(); 四、檢測EOF
  成員函式eof()用來檢測是否到達檔案尾,如果到達檔案尾返回非0值,否則返回0。原型是int eof(); 例:  if(in.eof())   ShowMessage("已經到達檔案尾!"); 五、檔案定位
  和C的檔案操作方式不同的是,C++ I/O系統管理兩個與一個檔案相聯絡的指標。一個是讀指標,它說明輸入操作在檔案中的位置;另一個是寫指標,它下次寫操作的位置。每次執行輸入或輸出時,相應的指標自動變化。所以,C++的檔案定位分為讀位置和寫位置的定位,對應的成員函式是seekg()和seekp()。seekg()是設定讀位置, seekp是設定寫位置。它們最通用的形式如下:     istream &seekg(streamoff offset,seek_dir origin);
    ostream &seekp(streamoff offset,seek_dir origin);   streamoff定義於 iostream.h 中,定義有偏移量 offset 所能取得的最大值,seek_dir 表示移動的基準位置,是一個有以下值的列舉: ios::beg:  檔案開頭
ios::cur:  檔案當前位置
ios::end:  檔案結尾   這兩個函式一般用於二進位制檔案,因為文字檔案會因為系統對字元的解釋而可能與預想的值不同。例:     file1.seekg(1234,ios::cur);    //把檔案的讀指標從當前位置向後移1234個位元組
file2.seekp(1234,ios::beg);    //把檔案的寫指標從檔案開頭向後移1234個位元組

這是MSDN中ofstream和ifstream的解釋:

ofstream::ofstream

ofstream();

ofstream( const char* szName, int nMode = ios::out, int nProt = filebuf::openprot );

ofstream( filedesc fd );

ofstream( filedesc fd, char* pch, intnLength );

Parameters

szName

The name of the file to be opened during construction.

nMode

An integer that contains mode bits defined as ios enumerators that can be combined with the bitwise OR (| ) operator. The nMode parameter must have one of the following values:

  • ios::app   The function performs a seek to the end of file. When new bytes are written to the file, they are always appended to the end, even if the position is moved with theostream::seekp function.

  • ios::ate   The function performs a seek to the end of file. When the first new byte is written to the file, it is appended to the end, but when subsequent bytes are written, they are written to the current position.

  • ios::in   If this mode is specified, then the original file (if it exists) will not be truncated.

  • ios::out   The file is opened for output (implied for all ofstream objects).

  • ios::trunc   If the file already exists, its contents are discarded. This mode is implied ifios::out is specified and ios::ate, ios::app, andios:in are not specified.

  • ios::nocreate   If the file does not already exist, the function fails.

  • ios::noreplace   If the file already exists, the function fails.

  • ios::binary   Opens the file in binary mode (the default is text mode).

nProt

The file protection specification; defaults to the static integerfilebuf::openprot that is equivalent to filebuf::sh_compat. The possiblenProt values are:

  • filebuf::sh_compat   Compatibility share mode.

  • filebuf::sh_none   Exclusive mode; no sharing.

  • filebuf::sh_read   Read sharing allowed.

  • filebuf::sh_write   Write sharing allowed.

    To combine the filebuf::sh_read and filebuf::sh_write modes, use the logical OR (|| ) operator.

fd

A file descriptor as returned by a call to the run-time function_open or _sopen; filedesc is atypedef equivalent to int.

pch

Pointer to a previously allocated reserve area of length nLength. ANULL value (or nLength = 0) indicates that the stream will be unbuffered.

nLength

The length (in bytes) of the reserve area (0 = unbuffered).

Remarks

The four ofstream constructors are:

Constructor Description
ofstream() Constructs an ofstream object without opening a file.
ofstream( const char*, int, int ) Contructs an ofstream object, opening the specified file.
ofstream( filedesc ) Constructs an ofstream object that is attached to an open file.
ofstream( filedesc, char*, int ) Constructs an ofstream object that is associated with afilebuf object. The filebuf object is attached to an open file and to a specified reserve area.

All ofstream constructors construct a filebuf object. The first three use an internally allocated reserve area, but the fourth uses a user-allocated area. The user-allocated area is not automatically released during destruction.

ofstream::ofstream

ofstream();

ofstream( const char* szName, int nMode = ios::out, int nProt = filebuf::openprot );

ofstream( filedesc fd );

ofstream( filedesc fd, char* pch, intnLength );

Parameters

szName

The name of the file to be opened during construction.

nMode

An integer that contains mode bits defined as ios enumerators that can be combined with the bitwise OR (| ) operator. The nMode parameter must have one of the following values:

  • ios::app   The function performs a seek to the end of file. When new bytes are written to the file, they are always appended to the end, even if the position is moved with theostream::seekp function.

  • ios::ate   The function performs a seek to the end of file. When the first new byte is written to the file, it is appended to the end, but when subsequent bytes are written, they are written to the current position.

  • ios::in   If this mode is specified, then the original file (if it exists) will not be truncated.

  • ios::out   The file is opened for output (implied for all ofstream objects).

  • ios::trunc   If the file already exists, its contents are discarded. This mode is implied ifios::out is specified and ios::ate, ios::app, andios:in are not specified.

  • ios::nocreate   If the file does not already exist, the function fails.

  • ios::noreplace   If the file already exists, the function fails.

  • ios::binary   Opens the file in binary mode (the default is text mode).

nProt

The file protection specification; defaults to the static integerfilebuf::openprot that is equivalent to filebuf::sh_compat. The possiblenProt values are:

  • filebuf::sh_compat   Compatibility share mode.

  • filebuf::sh_none   Exclusive mode; no sharing.

  • filebuf::sh_read   Read sharing allowed.

  • filebuf::sh_write   Write sharing allowed.

    To combine the filebuf::sh_read and filebuf::sh_write modes, use the logical OR (|| ) operator.

fd

A file descriptor as returned by a call to the run-time function_open or _sopen; filedesc is atypedef equivalent to int.

pch

Pointer to a previously allocated reserve area of length nLength. ANULL value (or nLength = 0) indicates that the stream will be unbuffered.

nLength

The length (in bytes) of the reserve area (0 = unbuffered).

Remarks

The four ofstream constructors are:

Constructor Description
ofstream() Constructs an ofstream object without opening a file.
ofstream( const char*, int, int ) Contructs an ofstream object, opening the specified file.
ofstream( filedesc ) Constructs an ofstream object that is attached to an open file.
ofstream( filedesc, char*, int ) Constructs an ofstream object that is associated with afilebuf object. The filebuf object is attached to an open file and to a specified reserve area.

All ofstream constructors construct a filebuf object. The first three use an internally allocated reserve area, but the fourth uses a user-allocated area. The user-allocated area is not automatically released during destruction.