C++文件读写操作(二)逐字符读取文本和逐行读取文本

来源:互联网 发布:max 软件下载 编辑:程序博客网 时间:2024/05/01 21:04
 

相关文章


C++文件读写操作(一)将字母表写入TXT文本文件 


C++文件读写操作(二)逐字符读取文本和逐行读取文本 


C++文件读写操作(三)如何统计文本的行数及如何读取文件某一行内容 


C++文件读写操作(四)读取文件数据到临时数组 


 
#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      i10      j11      k12      l13      m14      n15      o16      p17      q18      r19      s20      t21      u22      v23      w24      x25      y26      zProcess returned 0 (0x0)   execution time : 0.484 sPress any key to continue.*************************************************/