How do I read an entire file into a std::string in C++?

后端 未结 15 1942
余生分开走
余生分开走 2020-11-21 23:51

How do I read a file into a std::string, i.e., read the whole file at once?

Text or binary mode should be specified by the caller. The solution should b

15条回答
  •  天涯浪人
    2020-11-22 00:16

    I do not have enough reputation to comment directly on responses using tellg().

    Please be aware that tellg() can return -1 on error. If you're passing the result of tellg() as an allocation parameter, you should sanity check the result first.

    An example of the problem:

    ...
    std::streamsize size = file.tellg();
    std::vector buffer(size);
    ...
    

    In the above example, if tellg() encounters an error it will return -1. Implicit casting between signed (ie the result of tellg()) and unsigned (ie the arg to the vector constructor) will result in a your vector erroneously allocating a very large number of bytes. (Probably 4294967295 bytes, or 4GB.)

    Modifying paxos1977's answer to account for the above:

    string readFile2(const string &fileName)
    {
        ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);
    
        ifstream::pos_type fileSize = ifs.tellg();
        if (fileSize < 0)                             <--- ADDED
            return std::string();                     <--- ADDED
    
        ifs.seekg(0, ios::beg);
    
        vector bytes(fileSize);
        ifs.read(&bytes[0], fileSize);
    
        return string(&bytes[0], fileSize);
    }
    

提交回复
热议问题