Write byte to ofstream in C++
20,527
Solution 1
ofstream sw("C:\\Test.txt");
for(int i = 0; i < 256; i++)
{
sw << (int)myArray[i];
}
This will convert a char 'a' to an int(or byte) value 97.
Solution 2
To write a byte or a group of bytes using std::fstream or std::ofstream, you use the write()
function: std::ostream::write()
const int ArraySize = 100;
Byte byteArray[ArraySize] = ...;
std::ofstream file("myFile.data");
if(file)
{
file.write(&byteArray[0], ArraySize);
file.write(&moreData, otherSize);
}
Author by
Hlavson
Updated on March 02, 2020Comments
-
Hlavson about 4 years
I have char array, and i want to write it to txt file, but in bytes.
ofstream sw("C:\\Test.txt"); for(int i = 0; i < 256; i++) { sw << (byte)myArray[i]; }
This will write chars into the file, but i want to write bytes. If there is char 'a' i want to write '97'. Thank you.