C++實現簡單的檔案的讀寫
阿新 • • 發佈:2019-01-29
這裡的程式碼只是自己的筆記,也供別人參考。但請勿噴。
//C++實現檔案讀取 #include <fstream> int CountLines(const char *filename)//獲取檔案的行數 { ifstream ReadFile;//在標頭檔案fstream中 int n=0; string temp; ReadFile.open(filename,ios::in);//ios::in 表示以只讀的方式讀取檔案;如果filename是string型別,需要用c_str()函式轉換,因為filename的型別要求是const char *; if(ReadFile.fail())//檔案開啟失敗:返回0。該行程式碼可以換為:if(!ReadFile) { return 0; } else//檔案存在,返回檔案行數 { while(getline(ReadFile,temp))//將一行資訊讀入到temp中;或者是while(ReadFile>>temp),依次讀取單個字元。 { n++; } return n; } ReadFile.close(); return 0; } //以上程式碼實現的是,考察檔案裡面包含行內容
//C++實現檔案寫入 #include <fstream> void Write(const char *filename)//獲取檔案的行數 { ofstream OutFile;//在標頭檔案fstream中 int n=0; string temp; OutFile.open(filename,ios::out);//ios::out表示檔案不存在則建立,若檔案已存在則清空原內容;如果filename是string型別,需要用c_str()函式轉換,因為filename的型別要求是const char *; if(OutFile.fail())//檔案開啟失敗:返回0。該行程式碼可以換為:if(!OutFile) { return 0; } else//檔案存在,則寫入 { OutFile<<"要寫入的內容"<<endl; } OutFile.close(); return 0; }