分段故障(核心转储)

Jad*_*ida 0 c segmentation-fault

嘿家伙我有这个代码:(我试图读取一个字符串并将其放在输出文件中)

#include "structs.h"
#include <stdio.h>
#include <stdlib.h>
int main () {
  FILE* input = fopen("journal.txt", "r");
  FILE* output = fopen("output.txt", "w");
  char date[9];

  if( ferror(input) || ferror(output) ) {
    perror("Error opening input/output file\n");
  }

  fscanf(input, "%s", date);
  fgets(date, 9, input);
  fputs(date, output);
  fclose(input);
  fclose(output);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

它编译正确,但在运行时它显示错误

 Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)

我不明白为什么:(请帮助

Zet*_*eta 5

您需要检查是否fopen返回NULL:

#include <stdio.h>
#include <stdlib.h>
int main () {
  FILE * input;
  FILE * output;
  char date[9];

  input = fopen("journal.txt", "r");
  if(input == NULL){
    perror("Could not open input file");
    return -1;
  }

  output = fopen("output.txt", "w");
  if(output == NULL){
    perror("Could not open output file");
    fclose(input);
    return -1;
  }
/* ... snip ... */
Run Code Online (Sandbox Code Playgroud)

您的输入文件可能不存在.调用ferrorNULL的分割故障导致.