File Handling in C
File handling in C allows you to create, read, write, and modify files. C provides a set of functions to work with files through the stdio.h
library.
Types of Files
- Text Files - Store data in human-readable format.
- Binary Files - Store data in machine-readable format.
File Handling Functions
Function | Description |
---|---|
fopen() |
Opens a file |
fclose() |
Closes an open file |
fprintf() |
Writes data to a file (formatted) |
fscanf() |
Reads data from a file (formatted) |
fgets() |
Reads a line from a file |
fputs() |
Writes a line to a file |
fread() |
Reads binary data from a file |
fwrite() |
Writes binary data to a file |
Opening a File
The fopen()
function is used to open a file. It returns a FILE
pointer.
FILE *filePointer;
filePointer = fopen("example.txt", "w"); // Opens file in write mode
File Opening Modes
"r"
- Read"w"
- Write (overwrites if exists)"a"
- Append (adds data at the end)"r+"
- Read and write"w+"
- Write and read"a+"
- Append and read
Writing to a File
Use fprintf()
or fputs()
to write data.
FILE *file = fopen("data.txt", "w");
if (file != NULL) {
fprintf(file, "Hello, C File Handling!");
fclose(file);
}
Reading from a File
Use fscanf()
or fgets()
to read data.
FILE *file = fopen("data.txt", "r");
char content[100];
if (file != NULL) {
fgets(content, 100, file);
printf("%s", content);
fclose(file);
}
Closing a File
Use fclose()
to close the file and free resources.
fclose(file);
Understanding file handling is essential for data persistence in applications.
If you have any questions, feel free to ask. Thank you for reading!
If you have any query or question, please contact through below form. Our team will be in touch with you soon.
Please provide your valueable feedback or suggession as well.