在C++中将字节写入ofstream

Hla*_*son 1 c++ byte file char

我有char数组,我想把它写到txt文件,但是以字节为单位.

ofstream sw("C:\\Test.txt");
for(int i = 0; i < 256; i++)
{
  sw << (byte)myArray[i]; 
}
Run Code Online (Sandbox Code Playgroud)

这会将字符写入文件,但我想写字节.如果有char'a'我想写'97'.谢谢.

Jam*_*rey 8

要使用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);
}
Run Code Online (Sandbox Code Playgroud)