I'm trying to use ifstream/ofstream to read/write but for some reason, the data gets corrupted along the way. Heres the read/write methods and the test:
void FileWrite(const char* FilePath, std::vector<char> &data) { std::ofstream os (FilePath); int len = data.size(); os.write(reinterpret_cast<char*>(&len), 4); os.write(&(data[0]), len); os.close(); } std::vector<char> FileRead(const char* FilePath) { std::ifstream is(FilePath); int len; is.read(reinterpret_cast<char*>(&len), 4); std::vector<char> ret(len); is.read(&(ret[0]), len); is.close(); return ret; } void test() { std::vector<char> sample(1024 * 1024); for (int i = 0; i < 1024 * 1024; i++) { sample[i] = rand() % 256; } FileWrite("C:\\test\\sample", sample); auto sample2 = FileRead("C:\\test\\sample"); int err = 0; for (int i = 0; i < sample.size(); i++) { if (sample[i] != sample2[i]) err++; } std::cout << err << "\n"; int a; std::cin >> a; } It writes the length correctly, reads it correctly and starts reading the data correctly but at some point(depending on input, usually at around the 1000'th byte) it goes wrong and everything to follow is wrong. Why is that?
(reinterpret_cast<char*>(&len), 4)do not assume the size oflenis4. Instead usesizeof(len).