开发者

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

开发者 https://www.devze.com 2023-01-10 21:49 出处:网络
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

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 betwee开发者_开发知识库n it and the last thing written)?


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消