How to read a file into a string in C++

Method

  1. Open the file
  2. Seek to the end and use tell to find out how big it is
  3. Seek back to the beginning
  4. Construct a string with the length + 1 and fill it with nul characters so it’s nul-terminated
  5. Read the contents into the string’s buffer

You can do this using iostreams or stdio.

Using iostreams

    std::ifstream in(filename);
    if (in) {
        in.seekg(0, std::ios::end);
        size_t len = in.tellg();
        in.seekg(0);
        std::string contents(len + 1, '\0');
        in.read(&contents[0], len);
    }

Using stdio

    std::FILE* fptr = std::fopen(filename.c_str(), "r");
    if (fptr) {
        std::fseek(fptr, 0, SEEK_END);
        size_t len = std::ftell(fptr);
        std::fseek(fptr, 0, SEEK_SET);
        std::string contents(len + 1, '\0');
        std::fread(&contents[0], 1, len, fptr);
        fclose(fptr);
    }

Related

How to list the Files in a Directory in C++