使用 fopen() 时出现分段错误

Segmentation Fault when using fopen()

我不确定为什么会这样,但我从这个非常简单的代码中得到了 "Segmentation fault (core dumped)"。关于为什么的任何想法?我必须使用一个字符串来告诉 fopen() 打开什么文件。

#include <stdio.h>
#include <string.h>

int main(void) {
    char *small = "small.ppm";
    FILE * fp;
    char word[5];
    fp = fopen(small, "r");
    fscanf(fp, "%s", word);
    printf("%s\n", word);

    return 0;
}

您的代码可能会调用未定义的行为,替换为:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char *small = "small.ppm";
    FILE * fp = fopen(small, "r");
    if (fp == NULL) {
        perror("fopen()");
        return EXIT_FAILURE;
    }
    char word[5];
    if (fscanf(fp, "%4s", word) != 1) {
        fprintf(stderr, "Error parsing\n");
        return EXIT_FAILURE;
    }
    printf("%s\n", word);
}

如果文件不存在 fp 将为 NULL,因此 fscanf(fp, ...) 将出现段错误。

检查所有文件操作是否成功很重要。通常的模式是这样的……

FILE *fp = fopen(filename, "r");
if( fp == NULL ) {
    fprintf(stderr, "Couldn't open %s: %s\n", filename, strerror(errno));
    exit(1);
}