c++ 檔案io
阿新 • • 發佈:2019-02-20
c++中的檔案io,簡單的寫程式碼記錄下:
#include <iostream> #include <string> #include <fstream> using namespace std; //往文字檔案中寫入資料。 void write_content_file() { //如果text.txt檔案不存在,系統會自動新建一個text.txt檔案 //如果text.txt檔案存在了,系統會先把檔案清空,除非我們設定了 //開啟檔案的屬性:ios::app,那麼系統就會在檔案的末尾追加內容 ofstream fout("test.txt"); if (!fout) { cerr << "檔案開啟失敗" << endl; return; } //插入一個字串 fout << "hello , i am fine." << endl; //fout其實就是一個指標,此時,fout它指向了字串“hello , i am fine.”的末尾。 //所以當我們希望往檔案中插入新的資料時,它就會直接在最後追加。 int num = 1; fout << num << endl; fout.close(); } void read_content_file() { //把剛才的內容讀取出來 ifstream fin("test.txt"); //以讀檔案為目的開啟檔案,最容易出現問題 if (!fin) { cerr << "檔案開啟失敗" << endl; return; } //讀取一行的方法。 string str; while(getline(fin,str)) { if (str.length() > 3) { cout << str << endl; }else if(str.length()==1){ cout << "length is 1" << endl; }else{ cout<<"othrer"<<endl; } } fin.close(); } int main() { //write_content_file(); read_content_file(); return 0; }