So far the operations using the C program are done on a prompt/terminal which is not stored anywhere. But in the software industry, most programs are written to store the information fetched from the program. One such way is to store the fetched information in a file.
Different operations that can be performed on a file are :-
In order to understand why file handling makes programming easier, let us look at a few reasons :-
Examlpe : –
#include <stdio.h>
int main()
{
FILE *filePointer;
char data[100];
// Opening a file in write mode
filePointer = fopen(“example.txt”, “w”);
if (filePointer == NULL)
{
printf(“Unable to open the file.\n”);
return 1;
}
printf(“Enter data to write into the file: “);
fgets(data, sizeof(data), stdin);
// Writing data to the file
fprintf(filePointer, “%s”, data);
// Closing the file
fclose(filePointer);
printf(“Data written to the file successfully.\n”);
// Opening the file in read mode
filePointer = fopen(“example.txt”, “r”);
if (filePointer == NULL)
{
printf(“Unable to open the file.\n”);
return 1;
}
printf(“Reading data from the file:\n”);
// Reading data from the file
while (fgets(data, sizeof(data), filePointer) != NULL)
{
printf(“%s”, data);
}
// Closing the file
fclose(filePointer);
return 0;
}