Skip to content

Instantly share code, notes, and snippets.

@TimSC
Last active August 29, 2015 14:10
Show Gist options
  • Select an option

  • Save TimSC/ff5752c957408314a799 to your computer and use it in GitHub Desktop.

Select an option

Save TimSC/ff5752c957408314a799 to your computer and use it in GitHub Desktop.
Read an entire file in C++
#include <string>
#include <fstream>
#include <vector>
int ReadFileContents(const char *filename, int binaryMode, std::string &contentOut)
{
contentOut = "";
std::ios_base::openmode mode = (std::ios_base::openmode)0;
if(binaryMode)
mode ^= std::ios::binary;
std::ifstream file(filename, mode);
if(!file) return 0;
file.seekg(0,std::ios::end);
std::streampos length = file.tellg();
file.seekg(0,std::ios::beg);
std::vector<char> buffer(length);
file.read(&buffer[0],length);
contentOut.assign(&buffer[0], length);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment