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)?
Share
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
where
fpis the file pointer,SEEK_CURis a constant declared instdio.h, and18is 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
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.