C - 我对文件的写入丢失了

C - My writes to a file are lost

我接到了一项任务,要将一些行(通常发送到标准输入)写入我选择的 .txt 文件。

使用:

#include <stdio.h>
int main(){
FILE * henry;

henry = fopen ("henry.txt", "w");

fprintf(henry, "This is some test text to be printed to a file!");
}

这正确地输出到一个文件,它应该如此。但是,当简单地将其添加到下面的代码时,它会删除我要写入的文件中的所有当前文本,但实际上并没有写入!下面是我到目前为止的代码,但它缺少其他文件。但是光看有没有人知道为什么不输出到我指定的文件?

//critical_example2.c
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "se207_sems.h"

int main(int argc, char argv[]){
  FILE * henry;
  henry = fopen ("text.txt", "w");
  fprintf(henry, "This is some test text to be printed to a file!");
  //Use our source file as the "key"
  int id=se207_semget("critical_example2.c",1);

  int pid=fork();  
  if(pid ){
    //P1 = Process 1 is Henry.
    while(1){
      se207_wait(id); printf("There's a hole in the bucket, dear Liza, dear Liza,\n");
      rsleep();       printf("There's a hole in the bucket, dear Liza, a hole.\n");

      se207_signal(id);

      se207_wait(id); printf("With what shall I fix it, dear Liza, dear Liza?\n");
      rsleep();       printf("With what shall I fix it, dear Liza, with what?\n");

      se207_signal(id);

      se207_wait(id); printf("The straw is too long, dear Liza, dear Liza,\n");
      rsleep();       printf("The straw is too long, dear Liza, too long.\n");

      se207_signal(id);

      se207_wait(id); printf("With what shall I cut it, dear Liza, dear Liza?\n");
      rsleep();       printf("With what shall I cut it, dear Liza, with what?\n");

      se207_signal(id);

    }
  }else{
    //P2 = Process 2 is Liza
    while(1){
      se207_wait(id); fprintf(stderr, "Then fix it, dear Henry, dear Henry, dear Henry,\n");
      rsleep();       fprintf(stderr, "Then fix it, dear Henry, dear Henry, fix it.\n");
      //fprintf added to all of Liza's lines, with the location stderr being specified for output.
      se207_signal(id);

      se207_wait(id); fprintf(stderr, "With straw, dear Henry, dear Henry, dear Henry,\n");
      rsleep();       fprintf(stderr, "With straw, dear Henry, dear Henry, with straw.\n");

      se207_signal(id);

      se207_wait(id); fprintf(stderr, "Then cut it, dear Henry, dear Henry, dear Henry,\n");
      rsleep();       fprintf(stderr, "Then cut it, dear Henry, dear Henry, cut it.\n");

      se207_signal(id);

      se207_wait(id); fprintf(stderr, "With an axe, dear Henry, dear Henry, dear Henry,\n");
      rsleep();       fprintf(stderr, "With an axe, dear Henry, dear Henry, an axe.\n");

      se207_signal(id);
    }
  }
}

您需要调用 fflush():

fflush(henry);

fclose():

fclose(henry);

在你写完之后在你的 FILE* 变量上。否则,就像@AndrewHenie 建议的那样,数据可能会保留在您的进程的缓冲区中,而不会在您的程序终止之前实际写入。

重要:您的代码不会检查 henry 是非 NULL - 它可能是,失败!同样,您应该检查 fflush()fclose() 的 return 值。