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

来源:互联网 发布:淘宝网实拍保护网址 编辑:程序博客网 时间:2024/06/08 07:03

实现将文件读取到一个字符串中,已用来输出,可以使用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;

}

 

原创粉丝点击