阅读文件内容的问题

时间:2011-05-10 11:50:33

标签: c++ gtkmm

我有一个包含文字的文件。我逐行读取整个文件并附加到字符串对象。但是当我得到最后的字符串打印时,我没有得到整个文件内容。我确信这是由于存在特殊字符,如'\ n','\ r','\ t'等。

这是我的示例代码:

// Read lines until end of file (null) is reached
do
{
    line = ""; 
    inputStream->read_line(line);

    cout<<"\n "<<line;//here i get the content of each line
    fileContent.append(line);// here i am appending
}while(line.compare("") != 0);

2 个答案:

答案 0 :(得分:1)

这是用C ++读取文件到内存的方法:

#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;

int main() {
    vector <string> lines;
    ifstream ifs( "myfile.txt" );
    string line;
    while( getline( ifs, line ) ) {
         lines.push_back( line );
    }
    // do something with lines
}

答案 1 :(得分:1)

你必须向我展示更多代码才能知道你的问题是什么。

如果您将整个文件读入单个字符串,这是我通常使用的方法:

#include <string>
#include <fstream>
#include <iterator>

std::string read_file(const char *file_name)
{
    std::filebuf fb;

    if(!fb.open(file_name, std::ios_base::in))
    {
        // error.
    }

    return std::string(
        std::istreambuf_iterator<char>(&fb),
        std::istreambuf_iterator<char>());
}
相关问题