插入数据在C文件 [英] Inserting data to file in c

查看:140
本文介绍了插入数据在C文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个现有的文件之前,45 添加一个字符串个字节。我试着用 fseek的如下图所示。

I need to add a string before the 45th byte in an existing file. I tried using fseek as shown below.

int main()
{
    FILE *fp;
    char str[] = "test";     

    fp = fopen(FILEPATH,"a");
    fseek(fp,-45, SEEK_END);                
    fprintf(fp,"%s",str);
    fclose(fp);     
    return(0);
}

我预计这一code将前加测试的45 字符从EOF,相反,它只是追加测试到EOF。

I expected that this code will add "test" before the 45th char from EOF, instead, it just appends "test" to the EOF.

请帮我找到解决方案。

Please help me to find the solution.

这是我的previous问题结果的延续
追加项目在C最后一行前一个文件

This is continuation of my previous question
Append item to a file before last line in c

推荐答案

与模式R +打开它(如果它已经存在)或+(如果它不存在,你想创建一个)。既然你寻求45个字节的文件结束之前,我假设它已经存在。

Open it with mode r+ (if it already exists) or a+ (if it doesn't exist and you want to create it). Since you're seeking to 45 bytes before the end of file, I'm assuming it already exists.

fp = fopen(FILEPATH,"r+");

您code的其余部分是好的。另外请注意,这不会的插入的文本,但将覆盖目前无论是在文件在那个位置。

The rest of your code is fine. Also note that this will not insert the text, but will overwrite whatever is currently at that position in the file.

也就是说,如果你的文件看起来是这样的:

ie, if your file looks like this:

xxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx

然后运行该code之后,它看起来是这样的:

Then after running this code, it will look like this:

xxxxxxxtestxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx

如果你真的想插入和不覆盖,那么你需要从SEEK_END-45阅读所有文字到EOF到内存中,写的测试的,然后写文本带回

If you really want to insert and not overwrite, then you need to read all the text from SEEK_END-45 to EOF into memory, write test and then write the text back

这篇关于插入数据在C文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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