首页 > 解决方案 > C:当我想打开和写入文件时,如何解决“分段错误”?

问题描述

我正在尝试打开一个文件,但我既没有将“r”切换为“rt”,也没有将“at+”切换为“fp”总是返回 NULL。在我输入一个字符串后,输出将是一个分段错误。我犯的错误在哪里?请帮帮我

#include <stdio.h>
#include <string.h>
int main(){
    FILE *fp;
    char str[120] = {0}, strTemp[100];
    if( (fp=fopen("/User/don/Vim/code.c", "at+")) == NULL ){
        printf("Cannot open file\n");
    }
    printf("Input a string:");
    gets(strTemp);
    strcat(str, "\n");
    strcat(str, strTemp);
    fputs(str, fp);
    fclose(fp);
    return 0;
}

预期输出:

 Input a string: hello

实际输出:

 Cannot open file
 Input a string: hello
 Segmentation fault: 11

标签: c

解决方案


代替

if( (fp=fopen("/User/don/Vim/code.c", "at+")) == NULL ){
    printf("Cannot open file\n");
}

经过

if( (fp=fopen("/User/don/Vim/code.c", "at+")) == NULL ){
    printf("Cannot open file\n");
    return 0;
}

否则你将在 in 之后使用空指针fputs(str, fp);

正如 Jabberwocky 所说,gets很危险,因为你可以溢出缓冲区,使用fgets更安全

当然你也可以在一个else分支中做你的工作:

#include <stdio.h>
#include <string.h>
int main(){
  FILE *fp;
  char str[120] = {0}, strTemp[100];
  if( (fp=fopen("/User/don/Vim/code.c", "at+")) == NULL ){
    printf("Cannot open file\n");
  }
  else {
    printf("Input a string:");
    fgets(strTemp, sizeof(strTemp), stdin);
    strcat(str, "\n");
    strcat(str, strTemp);
    fputs(str, fp);
    fclose(fp);
  }

  return 0;
}

推荐阅读