用C覆盖文件中的行

KáG*_*áGé 2 c file overwrite line

我正在大学操作系统课程上进行文件系统项目,我的C程序应该在人类可读的文件中模拟一个简单的文件系统,所以文件应该基于行,一行将是一个"扇区".我已经知道,线条必须具有相同的长度才能被覆盖,因此我将用ascii零填充它们直到线的末尾并留下一定数量的ascii零线,以后可以填充.

现在我正在制作一个测试程序,看看它是否像我想要的那样工作,但它没有.我的代码的关键部分:

file = fopen("irasproba_tesztfajl.txt", "r+"); //it is previously loaded with 10 copies of the line I'll print later in reverse order  

  /* this finds the 3rd line */
 int count = 0; //how much have we gone yet?
 char c;

 while(count != 2) {
  if((c = fgetc(file)) == '\n') count++;
 }

 fflush(file);

 fprintf(file, "- . , M N B V C X Y Í ? Á É L K J H G F D S A Ú ? P O I U Z T R E W Q Ó Ü Ö 9 8 7 6 5 4 3 2 1 0\n");

 fflush(file);

 fclose(file);
Run Code Online (Sandbox Code Playgroud)

现在它什么也没做,文件保持不变.可能是什么问题呢?

谢谢.

Jac*_*cob 6

这里开始,

使用"+"选项打开文件时,您可以对其进行读写操作.但是,输入操作后可能不会立即执行输出操作; 你必须进行干预"倒带"或"fseek".同样,输出操作后可能不会立即执行输入操作; 你必须进行干预"倒带"或"fseek".

所以你已经实现了这一点fflush,但为了写到你需要fseek回来的所需位置.这就是我实现它的方式 - 我猜可能更好:

 /* this finds the 3rd line */
 int count = 0; //how much have we gone yet?
 char c;
 int position_in_file;

 while(count != 2) {
  if((c = fgetc(file)) == '\n') count++;
 }

 // Store the position
 position_in_file = ftell(file);
 // Reposition it
 fseek(file,position_in_file,SEEK_SET); // Or fseek(file,ftell(file),SEEK_SET);

 fprintf(file, "- . , M N B V C X Y Í ? Á É L K J H G F D S A Ú ? P O I U Z T R E W Q Ó Ü Ö 9 8 7 6 5 4 3 2 1 0\n");  
 fclose(file);
Run Code Online (Sandbox Code Playgroud)

另外,正如已经评论过的那样,您应该检查您的文件是否已成功打开,即在阅读/写入之前file,检查:

file = fopen("irasproba_tesztfajl.txt", "r+");
if(file == NULL)
{
  printf("Unable to open file!");
  exit(1);
}
Run Code Online (Sandbox Code Playgroud)