tags:

views:

75

answers:

3

Hi.

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

+4  A: 

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 == EACCESS) {
    // 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.

nos
thanks, this was just what I was looking for :D
Frxstrem
+2  A: 

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

Adam Batkin
+1  A: 

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.

ysth