This blog is under construction

Sunday, 28 July 2013

C program to read the contents of the given file

Write a C program to read the contents of the given file.


  #include <stdio.h>

  int main(int argc, char **argv) {
        int ch;
        FILE *fp;

        /* open the input file from the user */
        fp = fopen(argv[1], "r");

        /* incase file is not available */
        if (!fp) {
                printf("Unable to open the given file!!\n");
                return 0;
        }

        /* printing the contents of the input file in console */
        while (!feof(fp)) {
                ch = fgetc(fp);
                printf("%c", ch);
        }

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



  Output:
  jp@jp-VirtualBox:~/$ ./a.out data.txt 
  Take up one idea. Make that one idea your life -
  think of it, dream of it, live on that idea. Let 
  the brain, muscles, nerves, every part of your 
  body, be full of that idea, and just leave every 
  other idea alone. This is the way to success.

  jp@jp-VirtualBox:~/$ cat data.txt 
  Take up one idea. Make that one idea your life -
  think of it, dream of it, live on that idea. Let 
  the brain, muscles, nerves, every part of your 
  body, be full of that idea, and just leave every 
  other idea alone. This is the way to success.







SEE ALSO

    No comments:

    Post a Comment