Last active
May 28, 2020 18:15
-
-
Save ChunMinChang/b63710cbe4b18d8a4686a9d6f42ca4bd to your computer and use it in GitHub Desktop.
Read file into byte array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// image is from: https://github.com/rust-lang/rust/issues/11562 | |
#include <assert.h> // assert | |
#include <fstream> // std::ifstream | |
#include <vector> // std::vector | |
std::vector<char> file_to_bytes(const char* filename) { | |
// Seek to the end in advance to get the file size in an easier way. | |
std::ifstream ifs( | |
filename, std::ifstream::in | std::ifstream::binary | std::ifstream::ate); | |
assert(!ifs.fail()); | |
// Get size of the file. | |
std::streampos size = ifs.tellg(); | |
ifs.seekg(ifs.beg); // Rewind the cursor before reading data. | |
// Read the file data to byte array. | |
std::vector<char> buffer; | |
buffer.resize(size, 0); | |
assert(buffer.size() == size); | |
ifs.read(buffer.data(), static_cast<std::streamsize>(buffer.size())); | |
ifs.close(); | |
return buffer; | |
} | |
void bytes_to_file(const char* filename, std::vector<char> buffer) { | |
std::ofstream ofs(filename, std::ofstream::out | std::ofstream::binary); | |
assert(!ofs.fail()); | |
ofs.write(buffer.data(), static_cast<std::streamsize>(buffer.size())); | |
ofs.close(); | |
} | |
bool are_files_same(const char* file1, const char* file2) { | |
std::ifstream ifs1(file1, std::ifstream::binary | std::ifstream::ate); | |
std::ifstream ifs2(file2, std::ifstream::binary | std::ifstream::ate); | |
assert(!ifs1.fail() && !ifs2.fail()); | |
// Check file sizes.' | |
if (ifs1.tellg() != ifs1.tellg()) { | |
return false; | |
} | |
// Rewind files to their beginnings and compare their contents. | |
ifs1.seekg(ifs1.beg); | |
ifs2.seekg(ifs2.beg); | |
bool same = std::equal(std::istreambuf_iterator<char>(ifs1.rdbuf()), | |
std::istreambuf_iterator<char>(), | |
std::istreambuf_iterator<char>(ifs2.rdbuf())); | |
ifs1.close(); | |
ifs2.close(); | |
return same; | |
} | |
int main() { | |
const char* source = "rust-logo-256x256.png"; | |
const char* copy = "rust-logo-256x256_copy.png"; | |
std::vector<char> bytes = file_to_bytes(source); | |
bytes_to_file(copy, bytes); | |
assert(are_files_same(source, copy)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment