Differentiate between a unix directory and file in C and C++

后端 未结 4 1142

Given a path, say, /home/shree/path/def, I would want to determine if def is a directory or a file. Is there a way of achieving this in C or C++ code?

4条回答
  •  暖寄归人
    2020-12-05 11:06

    The following code uses the stat() function and the S_ISDIR ('is a directory') and S_ISREG ('is a regular file') macros to get information on the file. The rest is just error checking and enough to make a complete compilable program.

    #include 
    #include 
    #include 
    
    int main (int argc, char *argv[]) {
        int status;
        struct stat st_buf;
    
        // Ensure argument passed.
    
        if (argc != 2) {
            printf ("Usage: progName \n");
            printf ("       where  is the file to check.\n");
            return 1;
        }
    
        // Get the status of the file system object.
    
        status = stat (argv[1], &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]);
        }
    
        return 0;
    }
    

    Sample runs are shown here:

    
    pax> vi progName.c ; gcc -o progName progName.c ; ./progName
    Usage: progName 
           where  is the file to check.
    
    pax> ./progName /home
    /home is a directory.
    
    pax> ./progName .profile
    .profile is a regular file.
    
    pax> ./progName /no_such_file
    Error, errno = 2
    

提交回复
热议问题