当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《使用c++读取文本文件最优雅的方法是什么?》经验,为你挑选了2个好方法。

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

使用Python,我可以写:

text = open("text.txt", "rt").read()

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



1> Milan Babušk..:

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

读入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;
}

进入std :: string:

std::ifstream in("file.txt");
std::string contents((std::istreambuf_iterator(in)), 
    std::istreambuf_iterator());

进入vector :

std::ifstream in("file.txt");
std::vector contents((std::istreambuf_iterator(in)),
    std::istreambuf_iterator());

使用stringstream进入字符串:

std::ifstream in("file.txt");
std::stringstream buffer;
buffer << in.rdbuf();
std::string contents(buffer.str());

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


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

2> Konrad Rudol..:

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

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

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

string str((istreambuf_iterator(ifs)), istreambuf_iterator());

和快:

string str(static_cast(stringstream() << ifs.rdbuf()).str());

推荐阅读
无名有名我无名_593
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有