1.打開文件
1.1 fstream類型
1
2
3
4
|
#include <fstream> ofstream //文件寫操作 內(nèi)存寫入存儲設(shè)備 ifstream //文件讀操作,存儲設(shè)備讀區(qū)到內(nèi)存中 fstream //讀寫操作,對打開的文件可進行讀寫操作 |
1.2 open()的函數(shù)原型
1
2
3
4
5
6
|
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); |
參數(shù) | 含義 |
---|---|
filename | 操作文件名 |
mode | 打開文件的方式 |
prot | 打開文件的屬性 |
1.3 打開方式
打開文件的方式在ios類(所以流式I/O的基類)中定義,有如下幾種常用方式:
參數(shù) | 含義 |
---|---|
ios::in | 為輸入(讀)而打開文件 |
ios::out | 為輸出(寫)而打開文件 |
ios::ate | 初始位置:文件尾 |
ios::app | 所有輸出附加在文件末尾 |
ios::trunc | 如果文件已存在則先刪除該文件再重新創(chuàng)建 |
ios::binary | 二進制方式 |
1.4 打開文件的屬性
打開文件的屬性同樣在ios類中也有定義
參數(shù) | 含義 |
---|---|
0 | 普通文件,打開操作 |
1 | 只讀文件 |
2 | 隱含文件 |
4 | 系統(tǒng)文件 |
1.5 示例代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#include <iostream> #include <fstream> #include <iomanip> using namespace std; int main() { ofstream inFile; /*ios::trunc表示在打開文件前將文件清空,由于是寫入,文件不存在則創(chuàng)建*/ inFile.open( "inFile.txt" ,ios::trunc); int i; char a= 'a' ; for (i=1;i<=26;i++) //將26個數(shù)字及英文字母寫入文件 { inFile<<setw(2)<<i<< "\t" <<a<< "\n" ; a++; } inFile.close(); //關(guān)閉文件 } |
2.文本文件的讀寫
2.1 寫文件示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
// writing on a text file #include <fstream.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 |
2.2 讀文件示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
// 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() ) //eof到文件末尾返回true { in.getline (buffer,100); cout << buffer << endl; } return 0; } //結(jié)果 在屏幕上輸出 This is a line. This is another line |
2.3 逐字符讀取和逐行讀取
首先說說getline函數(shù),需要頭文件#include<string>
函數(shù)原型:istream& getline ( istream &is , string &str , char delim );
其中,istream &is 表示一個輸入流,譬如cin;
string&str表示把從輸入流讀入的字符串存放在這個字符串中(可以自己隨便命名,str什么的都可以);
char delim表示遇到這個字符停止讀入,在不設(shè)置的情況下系統(tǒng)默認該字符為'\n',也就是回車換行符
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
#include <iostream> #include <fstream> using namespace std; void testByChar() { fstream testByCharFile; char c; testByCharFile.open( "inFile.txt" ,ios::in); while (!testByCharFile.eof()) { testByCharFile>>c; cout<<c; } testByCharFile.close(); } void testByLine() { char buffer[256]; fstream outFile; outFile.open( "inFile.txt" ,ios::in); cout<< "inFile.txt" << "--- all file is as follows:---" <<endl; while (!outFile.eof()) { outFile.getline(buffer,256, '\n' ); //getline(char *,int,char) 表現(xiàn)該行字符達到256個或碰到換行就結(jié)束 cout<<buffer<<endl; } outFile.close(); } int main() { cout<<endl<< "逐個字符的讀取文件:testByChar() " <<endl<<endl; testByChar(); cout<<endl<< "將文件每行內(nèi)容存儲到字符串中,再輸出字符串 :testByLine()" <<endl<<endl; testByLine(); } |
2.4 統(tǒng)計文本行數(shù)及讀取某一行內(nèi)容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
//如何統(tǒng)計文本的行數(shù)及如何讀取文件某一行內(nèi)容: #include <iostream> #include <fstream> #include <string> using namespace std; int CountLines( char *filename) { ifstream in; int n=0; string tmp; in.open(filename,ios::in); //ios::in 表示以只讀的方式讀取文件 if (in.fail()) //文件打開失敗:返回0 { return 0; } else //文件存在 { while (getline(in,tmp, '\n' )) { n++; } in.close(); return n; } } string ReadLine( char *filename, int line) { int lines,i=0; string temp; fstream file; file.open(filename,ios::in); lines=CountLines(filename); if (line<=0) return "Error 1: 行數(shù)錯誤,不能為0或負數(shù)。" ; if (file.fail()) return "Error 2: 文件不存在。" ; if (line>lines) return "Error 3: 行數(shù)超出文件長度。" ; while (getline(file,temp)&&i<line-1) { i++; } file.close(); return temp; } int main() { int line; char filename[]= "inFile.txt" ; cout<< "該文件行數(shù)為:" <<CountLines(filename)<<endl; cout<< "\n請輸入要讀取的行數(shù):" <<endl; while (cin>>line) { cout<< "第" <<line<< "行的內(nèi)容是 :" <<endl; cout<<ReadLine(filename,line); cout<< "\n\n請輸入要讀取的行數(shù):" <<endl; } } /********************************** 程序運行情況如下: 該文件行數(shù)為:26 請輸入要讀取的行數(shù): -3 第-3行的內(nèi)容是 : Error 1: 行數(shù)錯誤,不能為0或負數(shù)。 請輸入要讀取的行數(shù): 4 第4行的內(nèi)容是 : 4 d 請輸入要讀取的行數(shù): 8 第8行的內(nèi)容是 : 8 h 請輸入要讀取的行數(shù): 26 第26行的內(nèi)容是 : 26 z 請輸入要讀取的行數(shù): 33 第33行的內(nèi)容是 : Error 3: 行數(shù)超出文件長度。 請輸入要讀取的行數(shù): 66 第66行的內(nèi)容是 : Error 3: 行數(shù)超出文件長度。 請輸入要讀取的行數(shù): ^Z **********************************/ |
2.5 讀取數(shù)據(jù)到數(shù)組當中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
//讀取文件數(shù)據(jù)到臨時數(shù)組 #include <iostream> #include <fstream> #include <string> using namespace std; int CountLines( char *filename) { ifstream ReadFile; int n=0; string tmp; ReadFile.open(filename,ios::in); //ios::in 表示以只讀的方式讀取文件 if (ReadFile.fail()) //文件打開失敗:返回0 { return 0; } else //文件存在 { while (getline(ReadFile,tmp, '\n' )) { n++; } ReadFile.close(); return n; } } int main() { ifstream file; int LINES; char filename[512]= "inFile.txt" ; file.open(filename,ios::in); if (file.fail()) { cout<< "文件不存在." <<endl; file.close(); } else //文件存在 { LINES=CountLines(filename); int *tempInt= new int [LINES]; char *tempChar= new char [LINES]; int i=0; while (!file.eof()) //讀取數(shù)據(jù)到數(shù)組 { file>>tempInt[i]; file>>tempChar[i]; i++; } file.close(); //關(guān)閉文件 for (i=0;i<LINES;i++) //輸出數(shù)組內(nèi)容 cout<<tempInt[i]<< "\t" <<tempChar[i]<<endl; delete []tempInt; delete []tempChar; } } |
3.狀態(tài)標志符的驗證(Verification of state flags)
-
bad() 如果在讀寫過程中出錯,返回 true
例如:當我們要對一個不是打開為寫狀態(tài)的文件進行寫入時,或者我們要寫入的設(shè)備沒有剩余空間的時候 -
fail()
除了與bad() 同樣的情況下會返回 true 以外,加上格式錯誤時也返回true ,例如當想要讀入一個整數(shù),而獲得了一個字母的時候 -
eof()
如果讀文件到達文件末尾,返回true -
good()
這是最通用的:如果調(diào)用以上任何一個函數(shù)返回true 的話,此函數(shù)返回 false
要想重置以上成員函數(shù)所檢查的狀態(tài)標志,你可以使用成員函數(shù)clear()
4.獲得和設(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ù)都被重載為兩種不同的原型:
1
2
|
seekg ( pos_type position ); seekp ( pos_type position ); |
使用這個原型,流指針被改變?yōu)橹赶驈奈募_始計算的一個絕對位置。要求傳入的參數(shù)類型與函數(shù) tellg 和tellp 的返回值類型相同。
1
2
|
seekg ( off_type offset, seekdir direction ); seekp ( off_type offset, seekdir direction ); |
使用這個原型可以指定由參數(shù)direction決定的一個具體的指針開始計算的一個位移(offset)。它可以是:
參數(shù) | 含義 |
---|---|
ios::beg | 從流開始位置計算的位移 |
ios::cur | 從流指針當前位置開始計算的位移 |
ios::end | 從流末尾處開始計算的位移 |
流指針 get 和 put 的值對文本文件(text file)和二進制文件(binary file)的計算方法都是不同的,因為文本模式的文件中某些特殊字符可能被修改。由于這個原因,建議對以文本文件模式打開的文件總是使用seekg 和 seekp的第一種原型,而且不要對tellg 或 tellp 的返回值進行修改。對二進制文件,你可以任意使用這些函數(shù),應(yīng)該不會有任何意外的行為產(chǎn)生。
使用樣例:
1
2
3
4
5
6
|
例子: file.seekg(0,ios::beg); //讓文件指針定位到文件開頭 file.seekg(0,ios::end); //讓文件指針定位到文件末尾 file.seekg(10,ios::cur); //讓文件指針從當前位置向文件末方向移動10個字節(jié) file.seekg(-10,ios::cur); //讓文件指針從當前位置向文件開始方向移動10個字節(jié) file.seekg(10,ios::beg); //讓文件指針定位到離文件開頭10個字節(jié)的位置 |
獲得一個二進制文件的大小:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
// 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. |
5.二進制文件
在二進制文件中,使用<< 和>>,以及函數(shù)(如getline)來操作符輸入和輸出數(shù)據(jù),沒有什么實際意義,雖然它們是符合語法的。
文件流包括兩個為順序讀寫數(shù)據(jù)特殊設(shè)計的成員函數(shù):write 和 read。第一個函數(shù) (write) 是ostream 的一個成員函數(shù),都是被ofstream所繼承。而read 是istream 的一個成員函數(shù),被ifstream 所繼承。類 fstream 的對象同時擁有這兩個函數(shù)。它們的原型是:
1
2
|
write ( char * buffer, streamsize size ); read ( char * buffer, streamsize size ); |
這里 buffer 是一塊內(nèi)存的地址,用來存儲或讀出數(shù)據(jù)。參數(shù)size 是一個整數(shù)值,表示要從緩存(buffer)中讀出或?qū)懭氲淖址麛?shù)。
讀取二進制文件示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// 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 |
6.緩存和同步(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)系的緩存或操作失敗。
到此這篇關(guān)于C++文件流讀寫操作詳解的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/m0_51371693/article/details/121546330