Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

file

unix

fopen

When I do:

FILE * fp = fopen("filename", "r");`  

How can I know the file pointer fp points to a file or a directory? Because I think both cases the fp won't be null. What can I do?

The environment is UNIX.

like image 702
lkkeepmoving Avatar asked Sep 10 '13 05:09

lkkeepmoving


1 Answers

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]);
    }
}
like image 59
No Idea For Name Avatar answered Oct 04 '22 16:10

No Idea For Name