gpt4 book ai didi

c - 如何使用 fopen 函数进行正确的错误处理

转载 作者:行者123 更新时间:2023-11-30 20:08:10 25 4
gpt4 key购买 nike

我编写了一个程序,要求用户输入文件的完整路径名。然后它将尝试从提供的路径名字符串打开该文件。我使用了大多数书籍推荐的标准错误检查,即如果 fopen() 返回 NULL 则关闭程序(如果文件不存在,它将执行此操作)。当我运行程序并在提示时输入一些随机字符(显然不是有效的文件名)时,我的程序因运行时错误而挂起,因为它试图打开该不存在的文件。

如果你的程序在调用 fopen() 时已经崩溃了,那么标准错误检查 (pfile == NULL) 的意义何在?请参阅下面的代码。

我使用 LabWindows CVI 2017 作为我的环境,它使用 clang 编译器。请参阅运行时错误的图像。

enter image description here

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

#define MAX 200

int main (void){

char buffer[MAX];
int len = 0;
FILE *pfile = NULL;

printf("please enter the full pathname of the file you wish to process.\n");

fgets(buffer, MAX, stdin);

len = strlen(buffer);

buffer[len - 1] = '\0';

pfile = fopen(buffer, "r");

if(pfile == NULL){
printf("not a valid filename, press any key to exit.");
getchar();
return -1;
}

int sum = 0;
int c = 0;

while((c = fgetc(pfile)) != EOF){
sum += sizeof(c);
}

printf("the size of your file is %d\n", sum);

getchar();

return 0;
}

最佳答案

正在进行正确的错误处理。您的程序在这方面是有效的。但是,您的 IDE 会进行一些额外的错误检查,这就是您所看到的行为的原因。

关于c - 如何使用 fopen 函数进行正确的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58141271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com