使用C++标准库实现文件的读取

实现将文件读取到一个字符串中,已用来输出,可以使用c++标准库。比如有以下文件

 

test.txt

Hello world,

------------------------------

这里是一个测试文件,

以测试使用c++ STL文件读取的情况

 

 

一开始尝试定义一个fstream对象fin进行输出的时候,但是会遇到碰到空格就停止的情况

         std::fstream fin;

         fin.open("test.txt",std::ifstream::in);

         string strFile;

         fin >> strFile;

         std::cout << strFile << std::endl;

 

后来尝试定义格式状态noskipws,结果问题依旧

         fin >> std::noskipws;

 

当然可以用getline循环读入每一行来获取文件的文本,但是这样好像麻烦了很多。后来搜索到两种很好的解决办法,一种是用我们的文件输入流定义输入流迭代器。然后直接用迭代器初始化字符串;另一种方法是用rdbuf函数重定义文件流到一个字符流,然后用这个字符流来初始化字符串。

         具体的实现代码如下:详细解释参考注释部分

 

Main.cpp

#include <iostream>

#include <fstream>

#include <sstream>

#include <string>

#include <iterator>

using namespace std;

 

//使用C++标准库实现文件的读取

int main()

{

     //--------------------------------------------------------

     //定义一个文件输入流对象

     fstream fin;

     fin.open("test.txt",ifstream::in);

     if(!fin)

     {

         cerr << "test.txt打开失败!" << endl;

         return -1;

     }

 

     cout << "方法1:使用输入迭代器" << endl;

     fstream::fmtflags oldFlag = fin.flags();

     fin >> noskipws;                               //忽视文件输入流中的空格;

     istream_iterator<char> itrBegin(fin),itrEnd;//定义一个输入迭代器

     string strFile1(itrBegin,itrEnd);              //使用两个迭代器作为参数构造string对象

     cout << strFile1 << endl;

     fin.flags(oldFlag);                                //恢复文件流

 

     //--------------------------------------------------------

 

     fstream fin2;

     fin2.open("test.txt",ifstream::in);

     if(!fin2)

     {

         cerr << "test.txt打开失败!" << endl;

         return -1;

     }

 

     cout << "/n/n方法2:使用重定向流" << endl;

     ostringstream sout_temp;                       //定义一个字符流输出流对象

     sout_temp << fin2.rdbuf();                     //将文件流重定向至字符流

     string strFile2(sout_temp.str());

     cout << strFile2 << endl;

 

     return 0;

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值