如何在特定位置写入文件?

joh*_*hye 1 c file

我有一个家庭作业,我们必须使用.txt文件.

这是我的文件示例:

约翰一书1234 558
2 Myke 2222 9876
......

我想覆盖文件中的558号码.给出了ID(1,2 ......).我一直在搜索,fopen()函数只提供开始和追加的参数.

小智 5

您可以使用fopen("filename","r + b")打开文件进行更新(以二进制模式).然后,您可以使用fseek设置下一步要写入的内容,并使用fwrite/fputs或类似内容来更新数据.

例如,假设你从一个看起来像这样的文件test.text开始

0123456789abcde
0123456789abcde
0123456789abcde
Run Code Online (Sandbox Code Playgroud)

你可以使用以下程序

#include <stdio.h>
int main(int argc, char **argv)
{
  FILE *f;
  if(!(f = fopen("./test.text", "r+b"))) //open the file for updating
    return -1;
  fseek(f, 16, SEEK_SET);//set the stream pointer 16 bytes from the start.
  const char message[] = "Hello, World!";
  fputs(message,f);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果就是

0123456789abcde
Hello, World!de
0123456789abcde
Run Code Online (Sandbox Code Playgroud)

您仍然需要首先在文件中搜索要替换的ID,并且当您想要将"558"替换为"12345"时可能会遇到问题,除非线路上有额外的空格来填充输出.因为您将开始覆盖下一行的数据.