简体   繁体   中英

Writing binary files C++, way to force something to be at byte 18?

I'm currently trying to write a .bmp file in C++ and for the most part it works, there is however, just one issue. When I start trying to save images with different widths and heights everything goes askew and I'm struggling to solve it, so is there any way to force something to write to a specific byte (adding padding in between it and the last thing written)?

Count how many bytes have been written. Write zeroes until the count hits 18. Then resume writing your real data.

There are several sort of obvious answers, such as keeping your data in memory in a buffer, then putting the desired value in as bufr[offset]=mydata; . I presume you want something a little fancier than that, because you are, for example, doing this in a streaming sort of application where you can't have the whole object in memory at the same time.

In that case, what you're looking for is the magic offered by fseek(3) and ftell(3) (see man pages ). Seek positions the file as a specific offset; tell gets the file's current offset. If it's a constant offset of 18, the you simply finish up with the file, and do

fseek(fp, 18L, SEEK_CUR)

where fp is the file pointer, SEEK_CUR is a constant declared in stdio.h , and 18 is the number 18.

Update

By the way, this is based on the system call lseek(2) . Something that confuses people (read "me", I never remember this until I have been searching) is there is no matching "ltell(2)" system call. Instead, to get the current file offset, you use

off_t offset;
offset = lseek(fp, 0L, SEEK_CUR);

because lseek returns the offset after its operation. The example code above gives us the offset after moving 0 bytes from the current offset, which is of course the current offset.

UPdate

aha, C++ . You said C. For C++, there are member functions for seek and tell. See the fstream man page.

If you are on Windows, everything comes to writing predefined structures: "Bitmap storage" .

Also there is an example that shows how they should be filled: "Storing an Image" .

If you are writing not-just-for-windows code then you can mimic these structs and fallow the guide.

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