2

我正在大学操作系统课程上做一个关于文件系统的项目,我的 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);

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

谢谢你。

4

1 回答 1

7

这里开始

当使用“+”选项打开文件时,您可以对其进行读写。但是,您不能在输入操作之后立即执行输出操作;您必须执行中间的“倒带”或“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);

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

file = fopen("irasproba_tesztfajl.txt", "r+");
if(file == NULL)
{
  printf("Unable to open file!");
  exit(1);
}
于 2010-03-24T19:19:38.010 回答