This blog is under construction

Wednesday 31 July 2013

C program to find the file type, permission, size and last modification date of the given file

Write a C program to find the file type, permission, size and last modification date of the given file.


  #include <stdio.h>
  #include <time.h>
  #include <sys/stat.h>
  #include <string.h>
  #define MAX 256

  int main() {
        FILE *fp;
        char fname[MAX];
        struct stat st;

        printf("Enter your file name:");
        scanf("%s", fname);

        /* check whether the given file exists  or not */
        fp = fopen(fname, "r");

        if (!fp) {
                printf("Given file does not exists!!\n");
                return 0;
        }

        /* getting the stat of the given file */
        stat(fname, &st);

        /* checking for the file type */
        printf("File Type: ");
        if (st.st_mode & S_IFREG) {
                printf("Regular file!!\n");
        } else if (st.st_mode & S_IFDIR) {
                printf("Directory!!\n");
        } else if (st.st_mode & S_IFLNK) {
                printf("Symbolic link!!\n");
        }

        printf("Owner Permission: ");
        /* checking for the owner permission */
        if (st.st_mode & S_IRUSR) {
                printf("\nRead Permission bit set!!\n");
        }

        if (st.st_mode & S_IWUSR) {
                printf("Write Permission bit set!!\n");
        }

        if (st.st_mode & S_IXUSR) {
                printf("Execute permission bit set!!\n");
        }

        printf("File Size: ");
        /* size of the file */
        printf("%d bytes", (int)st.st_size);

        printf("\nLast Modification Time: ");
        /* last modification time for the given file */
        printf("%s", ctime(&st.st_mtime));

        /* closing the opened file */
        fclose(fp);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your file name:data_part_1.txt
  File Type: Regular file!!
  Owner Permission: 
  Read Permission bit set!!
  Write Permission bit set!!
  File Size: 24 bytes
  Last Modification time: Wed Jul 31 22:21:37 2013

  jp@jp-VirtualBox:~/$ ls -l data_part_1.txt
  -rw-r--r-- 1 jp jp 24 2013-07-31 22:21 data_part_1.txt





SEE ALSO

    1 comment: