What is a File?
A file is a collection of data stored on a storage device, such as a hard disk or SSD. Files are
used to store data persistently, even after a program ends. In programming, files are typically
used for input/output operations.
File Operations
Files can be handled using various operations. The most common ones are:
1. Opening a File: Open a file in a specific mode (e.g., read, write).
r - Open for reading.
w - Open for writing (overwrites existing content).
a - Open for appending (adds to the end of the file).
r+, w+, a+ - Open for both reading and writing.
2. Reading from a File: Retrieve data from the file using functions like fgetc(), fgets(), or fscanf().
3. Writing to a File: Add content to the file using functions like fputc(), fputs(), or fprintf().
4. Closing a File: Close the file using fclose() to release resources.
---
C Program: Writing and Reading Text into a File
#include <stdio.h>
int main() {
FILE *filePointer;
char text[100];
filePointer = fopen("example.txt", "w");
if (filePointer == NULL)
{
printf("Error opening file for writing.\n");
return 1;
}
printf("Enter text to write into the file: ");
fgets(text, sizeof(text), stdin);
fprintf(filePointer, "%s", text);
fclose(filePointer);
printf("Text written to file successfully.\n");
filePointer = fopen("example.txt", "r");
if (filePointer == NULL)
{
printf("Error opening file for reading.\n");
return 1;
}
printf("Content of the file:\n");
while (fgets(text, sizeof(text), filePointer) != NULL)
{
printf("%s", text);
}
fclose(filePointer);
return 0;
}
---