When opening a file in append mode, how can I repo

2020-07-30 03:20发布

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.

标签: c fopen
1条回答
做个烂人
2楼-- · 2020-07-30 04:23

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.

查看更多
登录 后发表回答