简体   繁体   English

如何使用c ++逐字节写入文件

[英]How to write a file byte by byte using c++

How to write a file byte by byte using c++? 如何使用c ++逐字节写入文件?

unsigned short array[2]={ox20ac,0x20bc};

if i have a hexadecimal value 0x20ac how can i write it byte by byte in a file using c++ 如果我有一个十六进制值0x20ac我怎么能用c ++在一个文件中逐字节写它

You can try something like this: 你可以尝试这样的事情:

#include <fstream>
...

ofstream fout;
fout.open("file.bin", ios::binary | ios::out);

int a[4] = {100023, 23, 42, 13};
fout.write((char*) &a, sizeof(a));

fout.close();

One option, using standard C++ library: 一种选择,使用标准C ++库:

#include <fstream>
#include <assert.h>

void main()
{
    unsigned short array[2]={ox20ac,0x20bc};

    std::ofstream file;
    file.open("C:/1.dat", std::ios_base::binary);
    assert(file.is_open());

    for(int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
       file.write((char*)(array + i * sizeof(array[0])), sizeof(array[0]));
    file.close();
}

Alternatively, you can easily write your whole data in one go (without a loop): 或者,您可以轻松地一次性编写整个数据(无循环):

file.write((const char*)array, sizeof(array));

To open an output file, use ofstream (output file stream, a subclass of ostream). 要打开输出文件,请使用ofstream(输出文件流,ostream的子类)。 Use the ios_base::binary mode (as second argument in the constructor or the open() member function) if you're not sure whether your output is human-readable text (ASCII). 如果您不确定输出是否为人类可读文本(ASCII),请使用ios_base :: binary模式(作为构造函数中的第二个参数或open()成员函数)。

To write a single byte, use the ostream member function "put". 要写入单个字节,请使用ostream成员函数“put”。 To write more than one byte at a time, use the ostream member function "write". 要一次写入多个字节,请使用ostream成员函数“write”。

There are ways of taking data types (int, for example) longer than one byte and using them as arrays of bytes. 有一些方法可以使数据类型(例如int)长于一个字节并将它们用作字节数组。 This is sometimes called type-punning and is described in other answers, but beware of endianness and different sizes of data types (int can be 2-8 bytes), which can be different on different machines and compilers. 这有时被称为类型惩罚,并在其他答案中进行了描述,但要注意字节序和不同大小的数据类型(int可以是2-8个字节),这在不同的机器和编译器上可能不同。

To test your output, reopen it as an input file and print the bytes. 要测试输出,请将其重新打开为输入文件并打印字节。

ifstream in("myfile.txt", ios_base::binary);
while(!in.eof()) printf("%02X ", in.get()); //print next byte as a zero-padded width-2 capitalized hexadecimal).
in.close();

Or just use a hex editor like normal people. 或者像普通人一样使用十六进制编辑器。

you can use write function or ostream . 你可以使用写函数或ostream。 Use c++ function is ostream. 使用c ++函数是ostream。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM