包含頭文件ios
#include<fstream>(不帶擴展名「.h「)app
讀寫文件:ifstream(讀)、ofstream(寫)、fstream(讀寫):#include<ifstream>;#include<ofstream>;#include<fstream>,分別從istream、ostream、iostream中引伸而來的,因此fstream的對象能夠使用其父類成員來訪問數據。函數
獲取文件名spa
geetline(cin,filename,‘\n’);方式獲得用戶輸入的用戶名,其中filename爲String類型;與同控制檯(console)交互一樣的成員函數(cin&cout)來進行輸入輸出。.net
#inclulde<iostream> #include<fstream>//文件頭文件 #include<String> int main() { ifstream in;//ifstream讀文件 string filename;//文件名 getline(cin, filename, '\n');//獲取文件名,也能夠使用cin>>filename;可是不能獲取空格 in.open(filename); if(!in)//或if_open() { cerr<<"打開文件出錯"<<endl; return 1; } //逐個讀取字符 char ch; while(!in.eof())//到達文件尾時返回true { in.read(&ch, 1); cout<<ch; } in.close();//必須關閉文件 }
ofstream out("out.txt"); if (out.is_open()) { out << "This is a line.\n"; out << "This is another line.\n"; out.close(); }
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; }
open函數code
<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>
參數對象
filename | 操做文件名 |
mode | 打開文件的方式 |
prot | 打開文件的屬性 |
在ios類中文件的打開方式blog
ios::in | 爲輸入(讀)而打開文件 |
ios::out | 爲輸出(寫)而打開文件 |
ios::ate | 初始位置:文件尾 |
ios::app | 全部輸出附加在文件末尾 |
ios::trunc | 若是文件已經存在則先刪除已存在文件 |
ios::binary | 二進制方式 |
方式能夠使用」|「來隔開進行組合使用:in(」文件名.txt「, ios::in | ios::out | ios::binary);ci
ios類中打開文件的屬性定義get
0 | 普通文件,打開操做 |
1 | 只讀文件 |
2 | 隱含文件 |
4 | 系統文件 |
屬性能夠使用」+「來隔開進行組合使用
使用open默認方法(直接對流對象進行文件操做)
<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>
標誌性驗證(bool)
bad():過程當中出錯,返回true,如設備已滿
fail():在bad的功能基礎上,加上格式錯誤時也返回true
eof()
good():以上函數返回true時,函數返回false
(重置成員函數所檢查的狀態標誌,使用 .clear())
參考:【http://blog.csdn.net/kingstar158/article/details/6859379/】