C check if file exists

2019-01-19 11:20发布

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

I thought of using

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

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

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

标签: c c89
5条回答
别忘想泡老子
2楼-- · 2019-01-19 11:50

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 pretty wide standard I think.

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-19 11:54

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.

查看更多
beautiful°
4楼-- · 2019-01-19 11:56

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.

查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-19 11:58

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

查看更多
萌系小妹纸
6楼-- · 2019-01-19 12:02

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#).

查看更多
登录 后发表回答