This blog is under construction

Monday, 29 July 2013

C program to create, read, edit and close a file

Write a C program to create, read, edit and close a file.


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

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

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

        /* create/opening the input file in write mode */
        fp = fopen(str, "w");

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

        printf("Enter your input text:\n");

        /*
         * get the input characters from user
         * and write it to the output file.
         */
        while ((ch = getchar()) != EOF) {
                fputc(ch, fp);
        }

        /* closing the file */
        printf("Closing the edited file!!\n");
        fclose(fp);
        /* opening the file in read mode */
        fp = fopen(str, "r");

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

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

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

  }


Note: ctrl + d is EOF

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter any file name:editMe.txt
  Enter your input text:
  Stand up, be bold, be strong. Take the whole 
  responsibility on your own shoulders, and know that 
  you are the creator of your own destiny. All the 
  strength and succor you want is within yourself.    
  Therefore make your own future.
  Closing the edited file!!

  Content of the file editMe.txt:
  Stand up, be bold, be strong. Take the whole 
  responsibility on your own shoulders, and know that 
  you are the creator of your own destiny. All the 
  strength and succor you want is within yourself.    
  Therefore make your own future.






SEE ALSO

    No comments:

    Post a Comment