什么是最优雅的方式用c ++读取文本文件? [英] What is the most elegant way to read a text file with c++?

查看:165
本文介绍了什么是最优雅的方式用c ++读取文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



使用Python,我可以写:

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

我讨厌丑陋的东西,所以我想知道 - 什么是最优雅的方式用C ++阅读文本文件?
感谢。

解决方案

有很多方法,你选择哪一个是最优雅的。

读取到字符*:

  ifstream文件(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();
// ...做一些事情
delete [] content;
}

into std :: string:

  std :: ifstream in(file.txt); 
std :: string contents((std :: istreambuf_iterator< char>(in)),
std :: istreambuf_iterator< char>());

进入向量< char>:

  std :: ifstream in(file.txt); 
std :: vector< char> contents((std :: istreambuf_iterator< char>(in)),
std :: istreambuf_iterator< char>());

使用stringstream转换为字符串:

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

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


I'd like to read whole content of a text file to a std::string object with c++.

With Python, I can write:

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

It is very simple and elegant. I hate ugly stuff, so I'd like to know - what is the most elegant way to read a text file with C++? Thanks.

解决方案

There are many ways, you pick which is the most elegant for you.

Reading into 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;
}

Into std::string:

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

Into vector<char>:

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

Into string, using stringstream:

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

file.txt is just an example, everything works fine for binary files as well, just make sure you use ios::binary in ifstream constructor.

这篇关于什么是最优雅的方式用c ++读取文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆