This blog is under construction

Sunday, 28 July 2013

C program to check whether a directory exists or not

Write a C program to check whether a directory exists or not.


  #include <stdio.h>
  #include <dirent.h>

  int main(int argc, char **argv) {
        DIR *dir;
        struct dirent *ent;

        /* open the given directory */
        dir = opendir(argv[1]);

        /* if the given directory doesn't exists */
        if (!dir) {
                printf("Given directory does not exist!!\n");
        } else {
                /* if dir ptr is not NULL, then directory exists */
                printf("Given Directory Exists!!\n");
        }

        /* closing the given directory */
        closedir(dir);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ls
  a.out   done

  jp@jp-VirtualBox:~/$ ./a.out done/
  Given Directory Exists!!

  jp@jp-VirtualBox:~/$ ./a.out dir
  Given directory does not exist!!






SEE ALSO

    No comments:

    Post a Comment