How to distinguish a file pointer points to a file or a directory? How to distinguish a file pointer points to a file or a directory? unix unix

How to distinguish a file pointer points to a file or a directory?


i've found this near by:

#include <stdio.h>#include <errno.h>#include <sys/stat.h>int main (int argc, char *argv[]) {    int status;    struct stat st_buf;    status = stat ("your path", &st_buf);    if (status != 0) {        printf ("Error, errno = %d\n", errno);        return 1;    }    // Tell us what it is then exit.    if (S_ISREG (st_buf.st_mode)) {        printf ("%s is a regular file.\n", argv[1]);    }    if (S_ISDIR (st_buf.st_mode)) {        printf ("%s is a directory.\n", argv[1]);    }}


You could use fileno() to get the file discriptor for the already opened file, and then use fstat() on the file descriptor to have a struct stat returned.

It's member st_mode carries info on the file.

#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>int main(){  FILE * pf = fopen("filename", "r");  if (NULL == pf)  {    perror("fopen() failed");    exit(1);  }  {    int fd = fileno(pf);    struct stat ss = {0};    if (-1 == fstat(fd, &ss))    {      perror("fstat() failed");      exit(1);    }    if (S_ISREG (ss.st_mode))      {      printf ("Is's a file.\n");    }    else if (S_ISDIR (ss.st_mode))     {     printf ("It's a directory.\n");    }  }  return 0;}


On Windows, Call GetFileAttributes, and check for the FILE_ATTRIBUTE_DIRECTORY attribute.

Check this and this.