将文件加载到向量中< char> [英] Loading a file into a vector<char>
本文介绍了将文件加载到向量中< char>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将文本文件的内容加载到向量< char>
(或者任何字符输入迭代器,如果可能的话)。目前我的代码如下:
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());
}
我不喜欢手动使用缓冲区不是200,或25或任何?),或这需要大量的行。代码看起来很丑陋,非C ++。是否有更直接的方式这样做?
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?
推荐答案
如果你想避免读char by:
If you want to avoid reading char by char:
if (!file.eof() && !file.fail())
{
file.seekg(0, std::ios_base::end);
std::streampos fileSize = file.tellg();
vec.resize(fileSize);
file.seekg(0, std::ios_base::beg);
file.read(&vec[0], fileSize);
}
这篇关于将文件加载到向量中< char>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文