1.向文件寫數據
頭文件#include <ofstream>
①Create an instance of ofstream(創建ofstream實例)
②Open the file with open() or ofstreamconstructor (用open()或者構造函數打開文件)
③Writedata to the file with "<<" (用流插入運算符寫數據)
④Close the file (explicitly close()) (顯式地使用close()函數關閉文件)
若文件已存在,內容被直接清除。
1 #include <iostream> 2 #include <fstream> 3 using namespace std; 4 5 int main() 6 { 7 // ofstream output("score.txt"); 構造函數打開文件 8 ofstream output; 9 //創建文件 10 output.open("score.txt"); 11 //寫數據 output 類似於cout 12 output << "daidai" << " " << 90 << endl; 13 //關閉文件 14 output.close(); 15 return 0; 16 }
2.從文件讀數據
頭文件#include <ifstream>
①Create an instance of ifstream(創建ifstream對象)
②Open the file (use open() or ifstreamconstructor) (用open()函數或構造函數打開文件)
③Read data from the file with ">>" (用流提取運算符從文件讀數據)
④Close the file (explicitly using close() ) (顯式調用close()函數關閉文件)
1 #include <iostream> 2 #include <fstream> 3 using namespace std; 4 5 int main() 6 { 7 // ofstream output("score.txt"); 構造函數打開文件 8 ifstream input; 9 //打開文件 10 input.open("score.txt"); 11 //讀數據 input 12 char name[80]; 13 int score; 14 input >> name >> score; 15 cout << name << " " << score << endl; 16 //關閉文件 17 input.close(); 18 return 0; 19 }
3.格式控制
頭文件#include <iomanip>
①setw(width) 設置域寬
setw()控制符只對其后輸出的第一個數據有效,其他控制符則對其后的所有輸入輸出產生影響。
默認為setw(0),按實際輸出。
如果輸出的數值占用的寬度超過setw(int n)設置的寬度,則按實際寬度輸出。
Eg: cout<<setw(5)<<'a'<<'b'<<endl; 輸出: ab
float f=0.12345; cout<<setw(3)<<f<<endl; 輸出為0.12345
②setfill(c)
設置填充字符,即“<<"符號后面的數據長度小於域寬時,使用什么字符進行填充。
Eg: cout<<setfill('*')<<setw(5)<<'a'<<endl; 輸出:****a
③setprecision(int n)
可以控制顯示浮點數的有效位
n代表數字總位數
setprecision(0)的效果取決於編譯器。不同編譯器的實現是不同的。
本例中:
VC++2013輸出:2.42857
Dev C++ 5.6.0 (MinGW GCC 4.8.1)輸出: 2
④showpoint
將浮點數以帶小數點、帶結尾0 的形式輸出,即便它沒有小數部分
Eg:
float f1 = 13;
float f2 = 3.1415926;
float f3 = 5;
cout << showpoint << f1 << endl;
cout << showpoint << f2 << " " << f3 <<endl;
輸出:13.0000
3.14159 5.00000
⑤left 輸出內容左對齊
right 輸出內容右對齊
Eg:
cout << setw(5) << 13 << endl;
cout << setw(5) << right << 13 << endl;
cout << setw(5) << left << 13 << endl;
輸出: 13
13
13
⑥getline
getline(chararray[], intsize, chardelimitChar) //要寫入的數組,大小,分隔符
因為 >>運算符要求數據用空格分隔
1 #include <iostream> 2 #include <fstream> 3 using namespace std; 4 int main() 5 { 6 ifstream input("state.txt"); 7 char name[30]; 8 input >> name; 9 cout << name << endl; 10 return 0; 11 }
與預期不同。
1 //運用getline 2 #include <iostream> 3 #include <fstream> 4 using namespace std; 5 int main() 6 { 7 ifstream input("state.txt"); 8 char name[30]; 9 while(!input.eof()){ // Continue if not end of file 10 input.getline(name,40,'#'); 11 cout << name << endl; 12 } 13 return 0; 14 }
⑦ get: read a character
put:write a character
1 //copy get put 2 #include <iostream> 3 #include <fstream> 4 using namespace std; 5 int main() 6 { 7 cout << "Enter a source file name:"; 8 char inputFilename[20]; 9 cin >> inputFilename; 10 11 cout << "Enter a target file name:"; 12 char outputFilename[20]; 13 cin >> outputFilename; 14 15 ifstream input(inputFilename); 16 ofstream output(outputFilename); 17 18 while( !input.eof() ) { //Continue if not end of file 19 output.put(input.get()); 20 } 21 22 input.close(); 23 output.close(); 24 cout << "\nCopy Done" << endl; 25 return 0; 26 }
4.文件打開模式
fstream= ofstream+ ifstream
ofstream: write data
ifstream: read data
Mode Description
ios::in Opens a file for input. 讀模式
ios::out Opens a file for output. 寫模式
ios::app Appends all output to the end of the file. 追加模式
ios::ate Opens a file for output. If the file already exists, move to the end of the file. Data can be written anywhere in the file.
打開文件用於輸出。若文件存在則光標移至文件尾部。數據可以在任意位置寫入
ios::truct Discards the file’s contents if the file already exists. (This is the default action for ios:out).
若文件存在則丟棄其內容,這是ios:out的默認方式
ios::binary Opens a file for binary input and output.打開文件以二進制模式讀寫
模式組合: |
Eg:stream.open("state.txt", ios::out | ios::app);
5.測試流狀態
流狀態位 (Stream State Bit):These bit values (0or 1) indicate the state of a stream. (比特值指示流的當前狀態)
Bit When to set
ios::eofbit Set when the end of an input stream is reached. 到達文件末尾時
ios::failbit Set when an operation failed. 操作失敗時
ios::hardfail Set when an unrecoverable error occurred. 遇到不可恢復的錯誤時
ios::badbit Set when an invalid operation has been attempted. 試圖進行非法操作時
ios::goodbit Set when an operation is successful. 操作成功時
流狀態函數(Stream State Functions)
Function Description
eof() Returns true if the eofbit flag is set.
fail() Returns true if the failbit or hardfail flags is set.
bad() Returns true if the badbit is set.
good() Returns true if the goodbit is set.
clear() Clears all flags.
6.二進制讀寫
文本文件與二進制文件,都按二進制格式存儲比特序列
text file : interpretedas a sequence of characters (解釋為一系列字符)
binary file : interpretedas a sequence of bits. (解釋為一系列比特)
Eg: the decimal integer 199 (對於十進制整數199)
in text file: as the sequence of three characters, '1', '9', '9', (在文本文件中存為3個字符),stores as 3 bytes: 0x31, 0x39, 0x39 (三個字符的ASCII碼)
in bin file: as a byte-type value C7(decimal 199= hex C7 (在二進制文件中存為C7),stores as 1 bytes: 0xC7
ios::binary以二進制模式打開文件
文本模式讀寫函數
write: <<operator; put()
read : >>operator; get(); getline()
二進制模式讀寫函數
write: write(); streamObject.write(char* address, intsize)
read : read(); streamObject.read(char * address, intsize)
將任意類型數據寫入文件:轉換為字節流,write進去。
reinterpret_cast<dataType>(address) //將數據的地址轉換為為字符類型指針用於二進制讀寫
Eg:streamObject.write(reinterpret_cast<char *>, intsize);
char s[10]; streamObject.read(s, intsize);
int value; streamObject.read(reinterpret_cast<char*>(&value), sizeof(value));
double array[] = {1.1,2.2,3.3} streamObject.write(reinterpret_cast<char*>(array), sizeof(array));
Student stu1("kuotian",20,'f'), stu2;
streamObject.write(reinterpret_cast<char*>(&stu1), sizeof(Student));
streamObject.read(reinterpret_cast<char*>(&stu2), sizeof(Student));
7.
seekp, seekg, tellp, tellg
seek: 移動文件指針
tell:獲取文件指針位置
p: put,表示操作輸出文件中的指針
g: get,表示操作輸入文件中的指針
Seek Base Description
ios::beg Calculates the offset from the beginning of the file.
ios::end Calculates the offset from the end of the file.
ios::cur Calculates the offset from the current file pointer.
Statement Description
seekg(100L, ios::beg); Moves the file pointer to the 100th byte from the beginning of the file.
seekg(-100L, ios::end); Moves the file pointer to the 100th byte backward from the end of the file.
seekp(42L, ios::cur); Moves the file pointer to the 42nd byte forward from the current file pointer.
seekp(-42L, ios::cur); Moves the file pointer to the 42nd byte backward from the current file pointer.
seekp(100L); Moves the file pointer to the 100th byte in the file.