C program that demonstrates how to update file contents

#include <stdio.h>
#include <string.h>
int main()
 {
  FILE *fptr;
  char file_name[40];
  char text[800];
  printf("Enter the file name that you want to update: ");
  scanf("%s", file_name);
  file = fopen(file_name, "r");
  if (fptr == NULL)
   {
   printf("File is not available or name may be wrong.\n");
   return 1;
  }
  printf("Here is the content of your File:\n");
  while (fgets(text, 1000, fptr) != NULL)
   {
   printf("%s", text);
  }
  fclose(fptr);
  file = fopen(file_name, "w");
  if (fptr == NULL)
  {
   printf("Error while opening the file.\n");
   return 1;
  }
  printf("Enter any new text to update: ");
  getchar(); // clear the buffer
  fgets(text, 1000, stdin);
  fputs(text, fptr);
  printf("File has been successfully updated.\n");
  fclose(fptr);
  return 0;
 }


In this program given above, The message “Enter the file name that you want to update: “ is shown to the user to enter the filename , the file they want to update. The program open and then reads the current text of the file and displays that text to the user. The user can enter the new text that they want to modify or update to the file , and the program writes the new text to the file. At Last , the file is has been closed after successful updating the text.


Previous Topic:-->> Copy file in C. || Next topic:-->>count vowels in file.