This blog is under construction

Monday 29 July 2013

C program to create a file with input content

Write a C program to create a file with input content.


  #include <stdio.h>

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

        /* open the input file in write mode */
        fp = fopen(argv[1], "w");

        /* error handling */
        if (!fp) {
                printf("Unable to open the file %s\n", argv[1]);
                return 0;
        }

        /* write the string from command line argument to input file */
        fprintf(fp, "%s", argv[2]);

        printf("Written \" %s \" to the file %s\n", argv[2], argv[1]);

        /* closing the file */
        fclose(fp);

        /* open the input file in read mode */
        fp = fopen(argv[1], "r");

        /* error handling */
        if (!fp) {
                printf("Unable to open the file %s to read!!\n", argv[1]);
                return 0;
        }

        printf("\nContents in %s:\n", argv[1]);
        /* read the data from input file and write it on the console */
        while (!feof(fp)) {
                ch = fgetc(fp);
                if (ch != EOF) {
                        printf("%c", ch);
                }
        }
        printf("\n");

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


Input format:
<exe>  <filename>  <input string>   => ./a.out editMe.txt  HelloWorld

  Output:
  jp@jp-VirtualBox:~/$ ./a.out editMe.txt HelloWorld
  Written " HelloWorld " to the file editMe.txt
    
  Contents in editMe.txt:
  HelloWorld






SEE ALSO

    No comments:

    Post a Comment