C++ 将文件加载到 vector<char>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7241871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:39:59  来源:igfitidea点击:

Loading a file into a vector<char>

c++iostream

提问by Mankarse

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:

我想将文本文件的内容加载到 a vector<char>(或任何字符输入迭代器,如果可能的话)。目前我的代码如下所示:

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?

我不喜欢手动使用缓冲区(为什么是 100 个字符?为什么不是 200,或 25 或其他?),或者这需要大量的行。代码看起来非常丑陋且非 C++。有没有更直接的方法来做到这一点?

采纳答案by Flexo

Another approach, using rdbuf()to read the whole file to a std::stringstreamfirst:

另一种方法,用于rdbuf()首先读取整个文件std::stringstream

#include <fstream>
#include <sstream>
#include <vector>
#include <string>

// for check:
#include <algorithm>
#include <iterator>
#include <iostream>

int main() {
   std::ifstream file("test.cc");
   std::ostringstream ss;
   ss << file.rdbuf();
   const std::string& s = ss.str();
   std::vector<char> vec(s.begin(), s.end());

   // check:
   std::copy(vec.begin(), vec.end(), std::ostream_iterator<char>(std::cout));
}

回答by hamstergene

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);
}

回答by KillianDS

I think it's something like this, but have no environment to test it:

我认为它是这样的,但没有环境可以测试它:

std::copy(std::istream_iterator<char>(file), std::istream_iterator<char>(), std::back_inserter(vec));

Could be you have to play with io manipulators for things like linebreaks/whitespace.

可能你必须使用 io 操纵器来处理换行符/空格之类的事情。

Edit: as noted in comments, could be a performance hit.

编辑:如评论中所述,可能会影响性能。

回答by Adrien Plisson

use an iterator:

使用迭代器:

#include <iterator>

istream_iterator<char> data( file );
istream_iterator<char> end;
vec.insert( std::back_inserter(vec), data, end );

回答by Mankarse

There were lots of good responses. Thanks all! The code that I have decided on using is this:

有很多很好的回应。谢谢大家!我决定使用的代码是这样的:

std::vector<char> vec;
std::ifstream file;
file.exceptions(
    std::ifstream::badbit
  | std::ifstream::failbit
  | std::ifstream::eofbit);
//Need to use binary mode; otherwise CRLF line endings count as 2 for
//`length` calculation but only 1 for `file.read` (on some platforms),
//and we get undefined  behaviour when trying to read `length` characters.
file.open("test.txt", std::ifstream::in | std::ifstream::binary);
file.seekg(0, std::ios::end);
std::streampos length(file.tellg());
if (length) {
    file.seekg(0, std::ios::beg);
    vec.resize(static_cast<std::size_t>(length));
    file.read(&vec.front(), static_cast<std::size_t>(length));
}

Obviously, this is not suitable for extremely large files or performance-critical code, but it is good enough for general purpose use.

显然,这不适合超大文件或性能关键代码,但对于通用用途来说已经足够了。