This blog is under construction

Sunday 28 July 2013

C program to check whether a file exists or not

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


  #include <stdio.h>
  #include <unistd.h>
  #include <string.h>

  #define MAX 256

  int main() {
        char fname[MAX];

        /* get the file name from the user */
        printf("Enter your filename:");
        fgets(fname, MAX, stdin);
        fname[strlen(fname) - 1] = '\0';

        /* checking whether the given file exists or not */
        if (access(fname, F_OK) == -1) {
                printf("Given file does not exists!!\n");
        } else {
                printf("Given file Exists!!\n");
        }

        return 0;
  }



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

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your filename: data.txt
  Given file Exists!!






SEE ALSO

    No comments:

    Post a Comment