[英]Write byte to ofstream in C++
I have char array, and i want to write it to txt file, but in bytes. 我有char数组,我想将其写入txt文件,但以字节为单位。
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. 这会将chars写入文件,但我想写入字节。 If there is char 'a' i want to write '97'.
如果有字符'a',我想写'97'。 Thank you.
谢谢。
To write a byte or a group of bytes using std::fstream or std::ofstream, you use the write()
function: std::ostream::write () 要使用std :: fstream或std :: ofstream写入一个字节或一组字节,请使用
write()
函数: 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);
}
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. 这会将char'a'转换为int(或字节)值97。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.