C++檔案讀寫操作(三)如何統計文字的行數及如何讀取檔案某一行內容
阿新 • • 發佈:2019-01-10
相關文章
//如何統計文字的行數及如何讀取檔案某一行內容: #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; } } 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: 行數錯誤,不能為0或負數。"; } if(file.fail()) { return "Error 2: 檔案不存在。"; } if(line>lines) { return "Error 3: 行數超出檔案長度。"; } while(getline(file,temp)&&i<line-1) { i++; } file.close(); return temp; } int main() { int line; char filename[]="inFile.txt"; cout<<"該檔案行數為:"<<CountLines(filename)<<endl; cout<<"\n請輸入要讀取的行數:"<<endl; while(cin>>line) { cout<<"第"<<line<<"行的內容是 :"<<endl; cout<<ReadLine(filename,line); cout<<"\n\n請輸入要讀取的行數:"<<endl; } } /********************************** 程式執行情況如下: 該檔案行數為:26 請輸入要讀取的行數: -3 第-3行的內容是 : Error 1: 行數錯誤,不能為0或負數。 請輸入要讀取的行數: 4 第4行的內容是 : 4 d 請輸入要讀取的行數: 8 第8行的內容是 : 8 h 請輸入要讀取的行數: 26 第26行的內容是 : 26 z 請輸入要讀取的行數: 33 第33行的內容是 : Error 3: 行數超出檔案長度。 請輸入要讀取的行數: 66 第66行的內容是 : Error 3: 行數超出檔案長度。 請輸入要讀取的行數: ^Z Process returned 0 (0x0) execution time : 24.632 s Press any key to continue. **********************************/