File handling allows your C program to read data from, and write data to, permanent storage (like a hard drive) rather than just the console. All file operations in C rely on the standard library functions in <stdio.h>.
1. The File Pointer (FILE *)
In C, every operation on a file requires a file pointer, which is a pointer to a structure (FILE) defined in stdio.h. The file pointer manages all the information needed to control the file, such as its name, its location, and the position of the current read/write cursor.
Declaration:
FILE *fp; // fp is a pointer to a FILE structure
2. Opening a File (fopen)
Before any read or write operation, the file must be opened using the fopen() function. This function links the file pointer to the actual external file on the disk.
Syntax: FILE *fopen(const char *filename, const char *mode);
filename: The path and name of the file (e.g.,"data.txt").mode: A string specifying the intended operation.
File Opening Modes
| Mode String | Name | Description | Pointer Position | If File Doesn’t Exist |
"r" | Read | Opens file for reading only. | Start of file. | Returns NULL. |
"w" | Write | Opens file for writing only. | Start of file. | Creates the file, or truncates (clears) existing content. |
"a" | Append | Opens file for writing only. | End of file. | Creates the file. |
Example: Opening a file
FILE *fp = fopen("output.log", "w");
if (fp == NULL) {
// Crucial: check for errors (e.g., file not found, permission denied)
printf("Error opening file!\n");
return 1;
}
3. Writing Data to a File
A. Character-by-Character (fputc)
The fputc() function writes a single character to the file pointed to by the file pointer.
char ch = 'A';
fputc(ch, fp); // Writes 'A' to the file
B. Formatted Writing (fprintf)
The fprintf() function is identical to printf(), but its first argument is the file pointer, directing the output to the file instead of the console.
int num = 10;
fprintf(fp, "The final count is: %d\n", num);
4. Reading Data from a File
A. Character-by-Character (fgetc)
The fgetc() function reads a single character from the file pointed to by the file pointer and advances the cursor. It returns the character read or the constant EOF (End Of File) if the end is reached.
char ch;
// Loop until the End Of File marker is reached
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch); // Print character to console
}
B. Formatted Reading (fscanf)
The fscanf() function is identical to scanf(), but its first argument is the file pointer, reading formatted input from the file.
int file_number;
char file_word[20];
// Reads an integer and a string from the file
fscanf(fp, "%d %s", &file_number, file_word);
5. Closing a File (fclose)
When all operations are complete, the file must be closed using fclose(). This releases the file pointer, flushes any buffered data (ensuring data is actually written to disk), and releases system resources.
if (fp != NULL) {
fclose(fp);
}
