将文件加载到矢量中;
我想将文本文件的内容加载到 vector
(或任何字符输入迭代器,如果可能的话)。目前我的代码如下所示:
std::vector<char> vec;
std::ifstream file("test.txt");
assert(file.is_open());
while (!(file.eof() || file.fail())) {
char buffer[100];
file.read(buffer, 100);
vec.insert(vec.end(), buffer, buffer + file.gcount());
}
我不喜欢手动使用缓冲区(为什么是 100 个字符?为什么不是 200、25 或其他什么?),也不喜欢这需要大量的行。该代码看起来非常丑陋且非 C++。有更直接的方法吗?
I would like to load the contents of a text file into a vector<char>
(or into any char input iterator, if that is possible). Currently my code looks like this:
std::vector<char> vec;
std::ifstream file("test.txt");
assert(file.is_open());
while (!(file.eof() || file.fail())) {
char buffer[100];
file.read(buffer, 100);
vec.insert(vec.end(), buffer, buffer + file.gcount());
}
I do not like the manual use of a buffer (Why 100 chars? Why not 200, or 25 or whatever?), or the large number of lines that this took. The code just seems very ugly and non-C++. Is there a more direct way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果你想避免逐个字符地读取:
If you want to avoid reading char by char:
另一种方法是首先使用 rdbuf() 来将整个文件读取到 std::stringstream :
Another approach, using
rdbuf()
to read the whole file to astd::stringstream
first:我认为是这样的,但没有环境来测试它:
可能你必须使用 io 操纵器来处理诸如换行符/空格之类的事情。
编辑:正如评论中所述,可能会对性能造成影响。
I think it's something like this, but have no environment to test it:
Could be you have to play with io manipulators for things like linebreaks/whitespace.
Edit: as noted in comments, could be a performance hit.
有很多好的回应。谢谢大家!我决定使用的代码是这样的:
显然,这不适合非常大的文件或性能关键的代码,但对于一般用途来说已经足够了。
There were lots of good responses. Thanks all! The code that I have decided on using is this:
Obviously, this is not suitable for extremely large files or performance-critical code, but it is good enough for general purpose use.
使用迭代器:
use an iterator: