What is the most elegant way to read a text file with c++?(使用 C++ 读取文本文件的最优雅方式是什么?)
问题描述
我想用 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++ 读取文本文件的最优雅方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 C++ 读取文本文件的最优雅方式是什么?
基础教程推荐
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- c++ STL设置差异 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
