Update file contents in C language.
In C program , updating files usually means changing or altering the contents of a file. This may include adding new information to an existing file, modifying information in the file, or deleting information from the file.
To update files in C, you open the file in the appropriate mode (such as read, append or write), navigate to a specific location in the file you want to update, and then modify the data. Perform the necessary operations.
this may include reading and writing data using standard file functions such as fread() and fwrite() or positioning in file using function fseek().
Be careful when updating information inside file to keep it safe and avoid mistakes. Do not forget to save and close the file after making any changes.
Data updates in file must be carefully handled and monitored to prevent data corruption.
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.