C 檔案流操作

2021-10-02 06:05:35 字數 2503 閱讀 3656

在檔案流中, 定義的型別有:

fstream

既可以是輸入流也可以是輸出流

ifstream

輸入流ofstream

輸出流在對檔案進行操作前,需要以open的形式開啟,第乙個引數是filename, 第二個引數是mode

mode

含義ios::in

讀方式ios::out

寫方式一般結合寫方式,在文末尾進行追加

ios::ate

一般結合讀方式,指標跳到末尾

ios::trunc

以截斷方式開啟,也就是將檔案長度變為0

注意:1.當定義 ifstream 時, 預設以 ios::in 開啟;

2.當定義 ofstream 時, 預設以 ios::out|ios::trunc 開啟;

//嘗試向文字中寫資料

void

write()

文字中讀取資料方式總結:

1.按行讀取:

使用.getline()函式,遇到』\n』自動轉換為』\0』, 且讀取到eof時終止返回null

//文字中讀資料 一行一行的讀

void

readbyline()

fin.

close()

;}

2.按單詞讀取:

使用》流讀取,流讀取的過程中遇到空白時會結束,讀取到eof時返回null

//文字中讀資料 乙個單詞乙個單詞的讀

void

readbyword()

fin.

close()

;}

3.按字元讀取:

使用.get()函式讀取,get函式除了eof之外的字元都會進行讀取。

//文字中讀資料 乙個字元乙個字元的讀

void

readbychar()

fin.

close()

;}

流狀態位

含義goodbit

流狀態正常時為1

failbit

流狀態發生可挽回的錯誤,如讀取到eof字元等進行置位

badbit

當流發生不可挽回的錯誤時進行置位

eofbit

當讀取到終止符eof時進行置位

注意:當在讀取到eof將eofbit進行置位時,failbit也會進行置位

template

<

typename t>

void

showstate

(t& ss)

另外 clear函式可以將已經發生損壞了 的流進行恢復。

1.seekg 與 tellg:

這兩個函式都是針對於輸入流的操作

seekg函式官方解釋為:

basic_istream&

seekg

( pos_type pos )

;

表示從ios::beg,也就是開始的位置往後偏移pos個單位

basic_istream&

seekg

( off_type off, std::ios_base::seekdir dir)

;

off:為偏移量,為正時表示向後偏移,為負時表示向前偏移

dir:為起始位置,分為 ios::beg ios::cur ios::end 三種

tellg函式官方解釋為:

pos_type tellg()

;

表示返回目前流指標的位置,注意是輸入流的指標,當讀取失敗時返回-1

如下為測試用例:

//測試seekg與tellg,在已經讀到流末尾不進行clear的情況

void

test1()

//測試seekg與tellg,當流讀到末尾進行clear的情況

void

test2()

tellp與seekp: seekp的官方文件:

basic_ostream&

seekp

( pos_type pos )

;basic_ostream&

seekp

( off_type off, std::ios_base::seekdir dir )

;

tellp的官方文件:

pos_type tellp()

;

這兩個的使用原理與seekg 與 putg相似,就不再做過多闡述

測試用例如下:

//測試 seekp 與 tellp

void

test3()

C 檔案流操作

include stdafx.h include include include include include using namespace std void writecharsettofile const string filename void outputfile const strin...

C 檔案流操作

c 的檔案流本質是利用了乙個buffer中間層,有點類似標準輸出和標準輸入一樣。需要包含的標頭檔案 fstream.h 需要的命名空間 std fstream提供了三個類,用來實現c 對檔案的操作,以下對其做個簡要概述。1.ifstream類 2.ofstream類 3.fstream類 支援的檔案...

C 流檔案操作

c 流檔案操作 開發工具與關鍵技術 visual studio c 流檔案操作 流檔案的基本操作 1.開啟檔案 2.進行讀或者寫的操作 3.關閉檔案 計算機中各種應用系統都把一些資訊組織起來放在外部儲存器,這種組織被稱為檔案,並用檔名作為標識。c 中檔案作為無結構的位元組流 編碼方式 文字方式 二進...