This blog is under construction

Tuesday 30 July 2013

C program to check end of file

Write a C program to check end of file.


  #include <stdio.h>
  #include <string.h>
  #define MAX 256

  int main() {
        int ch;
        char fname[MAX], str[MAX];
        FILE *fp;

        /* get the input file name from the user */
        printf("Enter your input file:");
        scanf("%s", fname);

        /* open the input file in read mode */
        fp = fopen(fname, "r");

        printf("Reading file using fgetc:\n");
        /* reading the contents of input file */
        while (1) {
                ch = fgetc(fp);

                /* checking for end of file */
                if (ch == EOF) {
                        printf("End of file Reached!!\n");
                        break;
                } else {
                        printf("%c", ch);
                }
        }

        /* rewinding the file pointer to start of file */
        rewind(fp);

        printf("\nReading file using fgets:\n");

        /* reading the contents of input file line by line */
        while (1) {
                strcpy(str, "\0");
                fgets(str, MAX, fp);

                /* checking for end of file */
                if (feof(fp)) {
                        printf("End of file reached!!\n");
                        break;
                } else {
                        printf("%s", str);
                }
        }

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



  Output:
  jp@jp-VirtualBox:~/$ cat data.txt 
  abcdefghij
  klmnopqrst
  uvwxyz1234

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input file:data.txt
  Reading file using fgetc:
  abcdefghij
  klmnopqrst
  uvwxyz1234
  End of file Reached!!

  Reading file using fgets:
  abcdefghij
  klmnopqrst
  uvwxyz1234
  End of file reached!!






SEE ALSO

    No comments:

    Post a Comment