This blog is under construction

Monday, 29 July 2013

C program to append data into a file

Write a C program to append new data to a file.


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

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

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

        /* open the given input file in append mode */
        fp = fopen(fname, "a");

        /* error handling */
        if (!fp) {
                printf("Unable to open the given i/p file!!\n");
                return 0;
        }

        /* get the input string from the user to append to i/p file */
        printf("Enter the string you want to append:");
        fgets(str, MAX, stdin);
        str[strlen(str) - 1] = '\0';

        /* appending the input string to input file */
        fprintf(fp, "%s\n", str);

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



  Output:
  jp@jp-VirtualBox:~/$ cat output.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:~/$ ./a.out
  Enter your input file name:output.txt
  Enter the string you want to append: God is Great!!

  jp@jp-VirtualBox:~/$ cat output.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.

  God is Great!!






SEE ALSO

    No comments:

    Post a Comment