对文本内容读取的模式

对文本内容读取的方式

1.按照文本原来的格式全部读取显示:

1)

ifstream in(sourcefile, ios::in);
 istreambuf_iterator<char> beg(in), end;
 string content(beg, end);
 in.close();

 

2)

 fstream file;
  string line;
  string content;
  file.open(sourcefile);//输入的是D:\guo.txt
  if(!file)
  {
   g_Log.print(LogLevel_Info,"[SendHttp] open file fail.\n");
  }
  while(getline(file, line,"r")  {
  }

 (注意记得file.close(),要不然文件一直被占用着,如果要对文件做其他操作会导致失败的,比如文件的移动等)

2.去掉文本内容的换行

 fstream file;
  string line;
  string content;
  file.open(sourcefile);//输入的是D:\guo.txt
  if(!file)
  {
  }
  while(getline(file, line))//从文件中读取字符串到输入输出流中。不可以换成get()。while(getline(file, line,"r")
  {
   if (line!="")
   {
           content+=line;
   }

  }

 

3.头文件#include <fstream>