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

后端 未结 15 1949
余生分开走
余生分开走 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:19

    If you have C++17 (std::filesystem), there is also this way (which gets the file's size through std::filesystem::file_size instead of seekg and tellg):

    #include 
    #include 
    #include 
    
    namespace fs = std::filesystem;
    
    std::string readFile(fs::path path)
    {
        // Open the stream to 'lock' the file.
        std::ifstream f(path, std::ios::in | std::ios::binary);
    
        // Obtain the size of the file.
        const auto sz = fs::file_size(path);
    
        // Create a buffer.
        std::string result(sz, '\0');
    
        // Read the whole file into the buffer.
        f.read(result.data(), sz);
    
        return result;
    }
    

    Note: you may need to use and std::experimental::filesystem if your standard library doesn't yet fully support C++17. You might also need to replace result.data() with &result[0] if it doesn't support non-const std::basic_string data.

提交回复
热议问题