C check if file exists

浪子不回头ぞ 提交于 2019-11-28 11:59:48

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;

Edit: forgot to wrap fclose into a else

It's impossible to check existence for certain in pure ISO standard C. There's no really good portable way to determine whether a named file exists; you'll probably have to resort to system-specific methods.

This isn't a portable thing, so I'll give you OS-specific calls.

In Windows you use GetFileAttributes and check for a -1 return (INVALID_HANDLE or something like that).

In Linux, you have fstat to do this.

Most of the time however, I just do the file opening trick to test, or just go ahead and use the file and check for exceptions (C++/C#).

I guess this has more to do with system environment (such as POSIX or BSD) than with which version of C language you're using.

In POSIX there is a stat() syscall that will give you information about a file, even if you cannot read it. However, if the file is in path that you have no access permissions to it's always going to fail regardless of whether the file exists.

If you have no access to the path then it should never be possible to look on files contained.

k9dog

Do you really want to access the file? A check is usually better with the access(filename,F_OK)==0 from <unistd.h> and is a pretty wide standard, I think.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!