tags:

views:

36

answers:

1

I am trying to insert some data into the middle of a file. I have opened the file in append mode as:

file = fopen(msg->header.filename, "ab");

I then tried a seek to the desired offset in the file as so:

fseek(file, msg->header.offset, SEEK_SET);

However, when I then try an fwrite as so:

int bytesWritten = fwrite(msg->message, 1, msg->header.length, file);

All the data is written to the end of the file instead of in the middle of the file.

Is this because I am using append mode? I would open in write mode, but I need to keep the existing contents in the file.

+4  A: 

Look at the specification of ANSI C function fopen for "a" (APPEND) mode: All write operations take place at the end of the file. Your fseek will ignored.

Ahh, I thought it meant that the cursor would just start at the end. Didn't realize it would resist moving.
samoz
Yes. If you want to just start at the end, you need to open it in update (`rb+`) mode and call `fseek(f, 0, SEEK_END);`.
R..