简体   繁体   中英

How to write a file byte by byte using c++

How to write a file byte by byte using 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++

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:

#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). 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).

To write a single byte, use the ostream member function "put". To write more than one byte at a time, use the ostream member function "write".

There are ways of taking data types (int, for example) longer than one byte and using them as arrays of bytes. 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.

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 . Use c++ function is ostream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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