在c中将数据插入文件

发布于 2024-09-10 08:04:23 字数 541 浏览 5 评论 0原文

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

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

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

我预计这段代码会在 EOF 的第 45 个th 字符之前添加“test”,相反,它只是将“test”附加到 EOF。

请帮助我找到解决方案。

这是我之前问题的延续
将项目附加到 c 中最后一行之前的文件

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

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

懒猫 2024-09-17 08:04:23

使用模式 r+ (如果它已经存在)或 a+ (如果它不存在并且您想创建它)打开它。由于您正在寻找文件末尾之前的 45 个字节,因此我假设它已经存在。

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

你的其余代码都很好。另请注意,这不会插入文本,但会覆盖文件中当前该位置的任何内容。

即,如果您的文件如下所示:

xxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx

那么运行此代码后,它将如下所示:

xxxxxxxtestxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx

如果您确实想要插入而不是覆盖,那么您需要将从 SEEK_END-45 到 EOF 的所有文本读取到内存中,写入 < em>测试然后写回文本

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

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

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

xxxxxxxtestxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx

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

只有一腔孤勇 2024-09-17 08:04:23

如果您打算在任意位置写入,请勿将其作为附加 (a) 打开;它将强制所有写入到文件末尾。您可以使用r+在任何地方读取或写入。

Don't open it as append (a) if you plan to write at arbitrary positions; it will force all writes to the end of the file. You can use r+ to read or write anywhere.

淡淡の花香 2024-09-17 08:04:23

为了避免特定于平台的配置,请始终在 fopen() 调用中明确指示二进制或文本模式。

如果有一天您移植代码,这将为您节省数小时的绝望时间。

To avoid platform-specific configurations, always explicitely indicate the binary or text mode in your fopen() call.

This will save you hours of desperations if you port your code one day.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文