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

时间:2018-04-10 15:19:31

标签: c file file-io fopen

我已经完成了将一些行(通常发送到stdin)写入我选择的.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);
    }
  }
}

1 个答案:

答案 0 :(得分:4)

您需要拨打fflush()

fflush(henry);

fclose()

fclose(henry);
在您完成写作后,在FILE*变量上

。否则,就像@AndrewHenie建议的那样,数据可能会留在您的流程中。在程序终止之前,实际上不会写入缓冲区。

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