C++檔案讀寫操作(二)逐字元讀取文字和逐行讀取文字
阿新 • • 發佈:2019-01-25
相關文章
#include <iostream> #include <fstream> using namespace std; void testByChar() { fstream testByCharFile; char c; testByCharFile.open("inFile.txt",ios::in); while(!testByCharFile.eof()) { testByCharFile>>c; cout<<c; } testByCharFile.close(); } void testByLine() { char buffer[256]; fstream outFile; outFile.open("inFile.txt",ios::in); cout<<"inFile.txt"<<"--- all file is as follows:---"<<endl; while(!outFile.eof()) { outFile.getline(buffer,256,'\n');//getline(char *,int,char) 表示該行字元達到256個或遇到換行就結束 cout<<buffer<<endl; } outFile.close(); } int main() { cout<<endl<<"逐個字元的讀取檔案:testByChar() "<<endl<<endl; testByChar(); cout<<endl<<"將檔案每行內容儲存到字串中,再輸出字串 :testByLine()"<<endl<<endl; testByLine(); } /********************** 執行結果 逐個字元的讀取檔案:testByChar() 1a2b3c4d5e6f7g8h9i10j11k12l13m14n15o16p17q18r19s20t21u22v23w24x25y26zz 將檔案每行內容儲存到字串中,再輸出字串 :testByLine() inFile.txt--- all file is as follows:--- 1 a 2 b 3 c 4 d 5 e 6 f 7 g 8 h 9 i 10 j 11 k 12 l 13 m 14 n 15 o 16 p 17 q 18 r 19 s 20 t 21 u 22 v 23 w 24 x 25 y 26 z Process returned 0 (0x0) execution time : 0.484 s Press any key to continue. *************************************************/