Loading a file into a vector

前端 未结 5 475
后悔当初
后悔当初 2020-12-03 03:20

I would like to load the contents of a text file into a vector (or into any char input iterator, if that is possible). Currently my code looks like

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 03:51

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

    std::vector 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(length));
        file.read(&vec.front(), static_cast(length));
    }
    

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

提交回复
热议问题