File Handling in C
File Handling in C
File handling in C is a powerful feature that allows you to read, write, and
manipulate files. Files are used to store data permanently on storage media, unlike
variables, which are stored in RAM and are lost when the program terminates. In
C, files are represented using pointers of type `FILE *`, which are defined in the
`<stdio.h>` header.
1. **Text Files**:
- These files store data in human-readable form (ASCII characters).
- Each line of text is terminated with a newline character (`\n`), and each word or
number is separated by spaces or other delimiters.
2. **Binary Files**:
- These files store data in a binary format (machine-readable form).
- They are used for storing complex data like images, audio, or other binary data
without any transformation to readable text.
The `fopen()` function is used to open a file. It returns a pointer of type `FILE*`
which points to the file stream.
#### Syntax:
FILE *fopen(const char *filename, const char *mode);
Once a file operation is completed, the file must be closed to free system resources.
The `fclose()` function is used to close a file.
Syntax:
Example:
fclose(file_ptr);
Example:
char ch = fgetc(file_ptr);
Example:
char str[100];
fgets(str, 100, file_ptr);
printf("%s", str);
int num;
fscanf(file_ptr, "%d", &num);
Example:
int buffer[5];
fread(buffer, sizeof(int), 5, file_ptr);
Example:
fputc('A', file_ptr);
Example:
File positioning functions allow you to move the file pointer to a specific location
in the file.
Example:
Example: