C检文件是否存在 [英] C check if file exists

查看:150
本文介绍了C检文件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个项目中,我在C89标准我要检查文件是否存在做。
我该怎么做呢?

In a project I have to do in C89 standard I have to check if a file exists. How do I do this?

我想用的

FILE *file;
if ((file = fopen(fname, "r")) == NULL)
{
  printf("file doesn't exists");
}
return 0;

但我认为可以有更多的情况下,则文件不存在,将做的fopen == NULL。

but I think there can be more cases then file doesn't exists that will do fopen == NULL.

我如何做到这一点?我没有使用preFER包括而不是。

How do I do this? I prefer not using includes rather then .

推荐答案

如果您不能使用stat()在您的环境(这绝对是更好的方法),只是评估错误号。不要忘了包括errno.h中。

If you can't use stat() in your environment (which is definitely the better approach), just evaluate errno. Don't forget to include errno.h.

FILE *file;
if ((file = fopen(fname, "r")) == NULL) {
  if (errno == ENOENT) {
    printf("File doesn't exist");
  } else {
    // Check for other errors too, like EACCES and EISDIR
    printf("Some other error occured");
  }
} else {
  fclose(file);
}
return 0;

编辑:忘了FCLOSE封装成其他

这篇关于C检文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆