读取文件内容时出现问题

Issue with reading file content

本文关键字:问题 文件 读取      更新时间:2023-10-16

我有一个包含文本的文件。我逐行读取整个文件并附加到字符串对象。但是当我得到最终的字符串打印出来时,我没有得到整个文件内容。我确信这是由于存在特殊字符,例如""、"\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);
这是在

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
}

你必须显示更多的代码,让我知道你的问题是什么。

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

#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>());
}