在追加模式下打开文件时,如何重新定位文件指针? [英] When opening a file in append mode, how can I reposition the file pointer?

查看:244
本文介绍了在追加模式下打开文件时,如何重新定位文件指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在文件中间插入一些数据.我已经以附加模式打开文件,如下所示:

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);

但是,当我这样尝试fwrite时:

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.

推荐答案

查看"a"(APPEND)模式的ANSI C函数fopen的规范: 所有写入操作均在文件末尾进行. 你的fseek将被忽略.

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.

这篇关于在追加模式下打开文件时,如何重新定位文件指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆