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

后端 未结 15 1935
余生分开走
余生分开走 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-21 23:54

    Here's a version using the new filesystem library with reasonably robust error checking:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    namespace fs = std::filesystem;
    
    std::string loadFile(const char *const name);
    std::string loadFile(const std::string &name);
    
    std::string loadFile(const char *const name) {
      fs::path filepath(fs::absolute(fs::path(name)));
    
      std::uintmax_t fsize;
    
      if (fs::exists(filepath)) {
        fsize = fs::file_size(filepath);
      } else {
        throw(std::invalid_argument("File not found: " + filepath.string()));
      }
    
      std::ifstream infile;
      infile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
      try {
        infile.open(filepath.c_str(), std::ios::in | std::ifstream::binary);
      } catch (...) {
        std::throw_with_nested(std::runtime_error("Can't open input file " + filepath.string()));
      }
    
      std::string fileStr;
    
      try {
        fileStr.resize(fsize);
      } catch (...) {
        std::stringstream err;
        err << "Can't resize to " << fsize << " bytes";
        std::throw_with_nested(std::runtime_error(err.str()));
      }
    
      infile.read(fileStr.data(), fsize);
      infile.close();
    
      return fileStr;
    }
    
    std::string loadFile(const std::string &name) { return loadFile(name.c_str()); };
    

提交回复
热议问题