我想用 C++ 将文本文件的全部内容读取到 std::string
对象.
I'd like to read whole content of a text file to a std::string
object with c++.
使用 Python,我可以编写:
With Python, I can write:
text = open("text.txt", "rt").read()
它非常简单和优雅.我讨厌丑陋的东西,所以我想知道 - 用 C++ 读取文本文件的最优雅的方式是什么?谢谢.
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.
读入字符*:
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:
Into std::string:
std::ifstream in("file.txt");
std::string contents((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
转化为向量<字符>:
std::ifstream in("file.txt");
std::vector<char> contents((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
转成字符串,使用stringstream:
Into string, using stringstream:
std::ifstream in("file.txt");
std::stringstream buffer;
buffer << in.rdbuf();
std::string contents(buffer.str());
file.txt 只是一个例子,对于二进制文件一切正常,只要确保在 ifstream 构造函数中使用 ios::binary.
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++ 读取文本文件的最优雅方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!