LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   how to distinguish a file and a directory (https://www.linuxquestions.org/questions/programming-9/how-to-distinguish-a-file-and-a-directory-237402/)

joeyBig 10-01-2004 02:18 AM

how to distinguish a file and a directory
 
hi

I need to know how to distinguish between a file and a directory in a C program,
under Linux and Windows.
Is there any system calls to check if it is a directory?

regards,
joe.

rjlee 10-01-2004 03:50 AM

Try and open it using opendir:

Code:

#include <sys/types.h>
#include <dirent.h>
#incllude <errno.h>

//Returns 0 for directory, 1 for file, -1 for error in errno
//str is the pathname of the unknown file/directory
int isDirectory(char * str) {
  DIR dir;
  errno = 0;
  dir = opendir(str);
  if (dir != NULL) {
    closedir(dir);
    return 0;
  } else if (errno == ENOTDIR)
    return 1;
  } else return -1;
}


Hko 10-01-2004 04:21 AM

You can check the file type (regular file, dir, pipe, device, etc.) with stat() (see "man 2 stat").
Example:
Code:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char **argv)
{
    char *filename;
    int result;
    struct stat statinfo;

    if (argc != 2) {
                  fprintf(stderr, "Usage: %s [<file>]\n", argv[0]);
                  return 1;
    }
    filename = argv[1];
    result = lstat(filename, &statinfo);
    if (result < 0) {
                  if (errno == ENOENT) {
                          printf("File %s does not exist\n", filename);
                          return 0;
                  } else {
                          perror(*argv);
                          return 1;
                  }
    }
    printf("File %s exists, and is a ", filename);
    switch (statinfo.st_mode & S_IFMT) {
    case S_IFREG:  printf("regular file.\n"); break;
    case S_IFSOCK: printf("filesystem socket.\n"); break;
    case S_IFLNK:  printf("symbolic link.\n"); break;
    case S_IFBLK:  printf("block device file.\n"); break;
    case S_IFDIR:  printf("directory.\n"); break;
    case S_IFCHR:  printf("character device file.\n"); break;
    case S_IFIFO:  printf("filesystem pipe (fifo) file.\n"); break;
    default:  printf("unknown type of file.\n"); break;
    }
    return 0;
}

Note: Here lstat() is used instead of stat(), in order to be able to detect symbolic links.


All times are GMT -5. The time now is 08:59 AM.