简体   繁体   中英

How to find out if a file or directory exists?

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, named 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.

stat()函数应为您提供所需的一切(或更具体地讲lstat()因为stat()将跟随链接)。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM