File Handling in C - Short Notes
1. Introduction to File Handling
- File handling in C is used to store data permanently on a storage device.
- Types of files: Text files and Binary files.
2. File Operations
- Opening a File (fopen):
Syntax: FILE *fptr = fopen('filename', 'mode');
Modes: r, w, a, r+, w+, a+.
- Closing a File (fclose):
Syntax: fclose(fptr);
Frees the memory and ensures changes are saved.
3. File I/O Functions
- Reading from a File:
fgetc(), fgets(), fscanf().
- Writing to a File:
fputc(), fputs(), fprintf().
- Binary I/O:
fread(), fwrite().
4. Error Handling in Files
- Functions like feof(), ferror() are used for error detection.
5. File Pointers
- A pointer of type FILE* is used for handling files.
6. Example Program (Reading and Writing to a Text File):
#include <stdio.h>
int main() {
FILE *fptr;
char filename[] = 'example.txt';
fptr = fopen(filename, 'w');
if (fptr == NULL) {
printf('Error in opening file!');
return 1;
fprintf(fptr, 'Writing to a file.\n');
fclose(fptr);
return 0;