I'm using generator to make random sequence of unsigned __int8'ers, and then writing them to file using ofstream.write() with this method;
void CDataGenerator::GenerateRandom(std::string outputFileName, int length, bool UseEntireRange, int max) {
std::ofstream file;
file.open(outputFileName, std::ifstream::out | std::ifstream::binary);
int count = 0;
unsigned __int8* buf = new unsigned __int8[length];
while (count < length-1) {
int number = 0;
if (UseEntireRange)
number = rand();
else {
int rnd = rand();
number = (int)((double)rnd / RAND_MAX * max);
}
int capacity = 0;
if (number == 0)
capacity = 1;
else
capacity = (int)(floor(log10(number)) + 1);
for (int i = 0; i < capacity; ++i) {
if (count >= length - 2)
break;
buf[count] = ((unsigned __int8)(number / (int)pow(10, capacity - i - 1)));
number %= (int)pow(10, capacity - i - 1);
++count;
}
++count;
buf[count] = BCD_SEPARATOR;
}
file.write((__int8*)&buf[0], length);
delete[] buf;
file.close();
}
Where const static unsigned __int8 BCD_SEPARATOR = 0xff;
Then I try to read file with following method
unsigned __int8* CModel::GetRawData(std::string inputFileName, int &length) {
std::ifstream file(inputFileName, std::ifstream::ate | std::ifstream::binary);
length = file.tellg();
file.close();
file.open(inputFileName, std::ifstream::in | std::ifstream::binary);
unsigned __int8* result = new unsigned __int8[length];
file.read((__int8*)&result[0], length);
file.close();
return result;
}
Im my test generater creates sequence like this 0x0 0xFF 0x5 0x6 0xFF 0x1 0x9 0xFF 0x8 0xFF but from reading stream I get 0x0 0xCD 0x5 0x6 0xCD 0x1 0x9 0xCD 0x8 0xCD sequence. It's obvously that all 0xff are replaced with 0xcd. Is it connected with (__int8*) casts and How do I solve it?
int8_tfrom<cstdint>instead of the compiler-specific and non-portable__int8. I also recommend against using C-style casts in C++. Instead use something likereinterpret_cast<char*>(result). None of these things should relate to your problem though.