把二进制文件按字节读到vector中
1 std::vector<unsigned char> readFromFile1(const char* filePath) {
2 FILE* file = fopen(filePath, "rb");
3 std::vector<unsigned char> result;
4 if (file == nullptr) {
5 return result;
6 }
7
8 // 获取文件大小,尽量一次读完
9 size_t fileSize = getFileSize(file);
10 if (fileSize != 0) {
11 result.resize(fileSize);
12 size_t n = fread(&result[0], 1, fileSize, file);
13 assert(n <= fileSize);
14 if (n != fileSize) {
15 result.resize(n);
16 }
17 }
18
19 // 在读取过程当中,有可能文件大小有变化,再尝试读取
20 const size_t read_len = 1024;
21 char buf[read_len];
22 for (;;) {
23 size_t n = fread(buf, 1, read_len, file);
24 result.insert(result.end(), buf, buf + n);
25 if (n < read_len) {
26 break;
27 }
28 }
29 fclose(file);
30 return result;
31 }
32
33
另外一种C++风格,但是性能较差的方法:
1
2 std::vector<unsigned char> readFromFile2(const char* filePath) {
3 std::ifstream inputFile(filePath, std::ios::binary);
4 std::vector<unsigned char> fileData((std::istreambuf_iterator<char>(inputFile)),
5 std::istreambuf_iterator<char>());
6 return fileData;
7 }
8
9