Search code examples
cdirectoryargvargc

Whether a given file argument is a directory or not. C


I am looking for a peace of code to check if the argument I pass to my program is a directory or not. So far I found this:

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

int main(int argc, char *argv[])
{
    struct stat buf;

    stat(argv[1],&buf);

    exit(0);

}

But it does not really help me.


Solution

  • Use:

    if(S_ISDIR(buf.st_mode))
       printf(" Its a directoy\n");
    else
       printf("Its a file\n");
    

    after stat(argv[1],&buf); call