If you do it like the following (but properly wrapped up nicely unlike below), you can read in the file without worrying about a 0x1A byte in the file (for example) cutting the reading of the file short. The previously suggested methods will choke on a 0x1A (for example) in a file.
#include <iostream> #include <cstdio> #include <vector> #include <cstdlib> using namespace std; int main() { FILE* in = fopen("filename.txt", "rb"); if (in == NULL) { return EXIT_FAILURE; } if (fseek(in, 0, SEEK_END) != 0) { fclose(in); return EXIT_FAILURE; } const long filesize = ftell(in); if (filesize == -1) { fclose(in); return EXIT_FAILURE; } vector<unsigned char> buffer(filesize); if (fseek(in, 0, SEEK_SET) != 0 || fread(&buffer[0], sizeof(buffer[0]), buffer.size(), in) != buffer.size() || ferror(in) != 0) { fclose(in); return EXIT_FAILURE; } fclose(in); }
But, yeh, it's not an already-implemented 1-liner though.
Edit: 0x1A wasn't a good example as ios_base::binary will cover that. However, even then C++ streams often give me trouble when reading in png files all at once with .read(). Using the C way works better. Just can't remember a good example to show why. It was probably with .read()ing a binary file in blocks in a loop instead that can be a problem with C++ streams. So, disregard this post.