使用c ++读取文本文件最优雅的方法是什么?

Fan*_*Lin 57 c++ file-io text

我想std::string用c ++ 读取文本文件的全部内容到一个对象.

使用Python,我可以写:

text = open("text.txt", "rt").read()
Run Code Online (Sandbox Code Playgroud)

它非常简单而优雅.我讨厌丑陋的东西,所以我想知道 - 用C++读取文本文件最优雅的方法是什么?谢谢.

Mil*_*kov 126

有很多方法,你选择哪种方式最适合你.

读入char*:

ifstream file ("file.txt", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
    file.seekg(0, ios::end);
    size = file.tellg();
    char *contents = new char [size];
    file.seekg (0, ios::beg);
    file.read (contents, size);
    file.close();
    //... do something with it
    delete [] contents;
}
Run Code Online (Sandbox Code Playgroud)

进入std :: string:

std::ifstream in("file.txt");
std::string contents((std::istreambuf_iterator<char>(in)), 
    std::istreambuf_iterator<char>());
Run Code Online (Sandbox Code Playgroud)

进入vector <char>:

std::ifstream in("file.txt");
std::vector<char> contents((std::istreambuf_iterator<char>(in)),
    std::istreambuf_iterator<char>());
Run Code Online (Sandbox Code Playgroud)

使用stringstream进入字符串:

std::ifstream in("file.txt");
std::stringstream buffer;
buffer << in.rdbuf();
std::string contents(buffer.str());
Run Code Online (Sandbox Code Playgroud)

file.txt只是一个例子,一切都适用于二进制文件,只需确保在ifstream构造函数中使用ios :: binary.

  • 你实际上需要在内容'构造函数的第一个参数周围使用一组额外的括号,使用istreambuf_iterator <>来防止它被视为函数声明. (8认同)
  • @ Shadow2531:我认为在你用它完成任务之前不应删除它. (2认同)

Kon*_*lph 12

这个主题还有另一个主题.

我的解决方案来自这个线程(两个单行):

很好(见米兰的第二个解决方案):

string str((istreambuf_iterator<char>(ifs)), istreambuf_iterator<char>());
Run Code Online (Sandbox Code Playgroud)

和快:

string str(static_cast<stringstream const&>(stringstream() << ifs.rdbuf()).str());
Run Code Online (Sandbox Code Playgroud)