如何在 c 中尝试读取不存在的文件而不出现段错误?

问题描述 投票:0回答:1

我正在编写代码来检查文件是否真实并读取它是否真实

#include <stdio.h>
char file[100];
FILE* thefile;
int main(){
        thefile = fopen("what.txt", "r");
        if (thefile == NULL){
                printf("No File");
        } else {
                fgets(file, 100, thefile);
                printf("%s", file);
        }
        fclose(thefile);
        return 0;


}

它返回一个段错误,如果文件不存在,我将如何处理这个问题并且不打开文件?

我尝试将表达式移至 if 语句中,以及我能找到的所有教程。

c file-io segmentation-fault
1个回答
0
投票

如果对

fopen()
的调用失败,则应使用
fclose()
指针参数调用
NULL
,这将调用未定义的行为。

如果

fopen()
返回
NULL
,我们应该退出程序:

#include <stdlib.h> 

thefile = fopen("what.txt", "r");
if (thefile == NULL) {
    /* Write error messages to stderr. 
     * Calling strerror() or perror() can be more helpful. 
     */
    fprintf (stderr, "No File.\n"); 
    return EXIT_FAILURE; /* ADD. *?
}
/* Rest of the code. */
© www.soinside.com 2019 - 2024. All rights reserved.