开发者

How to find out if a file or directory exists?

开发者 https://www.devze.com 2023-01-12 20:25 出处:网络
I am trying to make a simple program that handles files and directories, but I have two major problems:

I am trying to make a simple program that handles files and directories, but I have two major problems:

  • how can I check whether a file or directory exists or not, and
  • how do I know if it is a file, directory, symbolic link, device, nam开发者_Go百科ed pipe etc.? Mainly file and directories matter for now, but I'd like to know the others too.

EDIT: Too all of those who are suggesting to use stat() or a similar function, I have already looked into that, and while it might answer my first question, I can't figure out how it would answer the second...


Since you're inquiring about named pipes/symlinks etc, you're probably on *nix, so use the lstat() function

struct stat info;

if(lstat(name,&info) != 0) {
  if(errno == ENOENT) {
   //  doesn't exist
   } else if(errno == EACCES) {
    // we don't have permission to know if 
   //  the path/file exists.. impossible to tell
   } else {
      //general error handling
   }
  return;
}
//so, it exists.

if(S_ISDIR(info.st_mode)) {
  //it's a directory
} else if(S_ISFIFO(info.st_mode)) {
  //it's a named pipe 
} else if(....) {
}

Se docs here for the S_ISXXX macros you can use.


The stat() function should give you everything you are looking for (or more specifically lstat() since stat() will follow the link).


Use stat (or if you wish to get information about a symbolic link instead of following it and getting information about the destination, lstat)

NAME

stat - get file status

SYNOPSIS

#include <sys/stat.h>

int stat(const char *restrict path, struct stat *restrict buf);

DESCRIPTION

The stat() function shall obtain information about the named file and write it to the area pointed to by the buf argument. The path argument points to a pathname naming a file. Read, write, or execute permission of the named file is not required. An implementation that provides additional or alternate file access control mechanisms may, under implementation-defined conditions, cause stat() to fail. In particular, the system may deny the existence of the file specified by path.

If the named file is a symbolic link, the stat() function shall continue pathname resolution using the contents of the symbolic link, and shall return information pertaining to the resulting file if the file exists.

The buf argument is a pointer to a stat structure, as defined in the header, into which information is placed concerning the file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号