File handling in C allows programs to read and write data to files, making it possible to store and retrieve information for later use. This tutorial covers the basics of opening, reading, writing, and closing files in C.
C uses the FILE
structure from stdio.h
for file operations. The basic file functions include:
fopen()
– Opens a file.fclose()
– Closes a file.fprintf()
– Writes formatted data to a file.fscanf()
– Reads formatted data from a file.fgets()
– Reads a line from a file.fputs()
– Writes a line to a file.The fopen()
function is used to open a file:
FILE *filePointer;
filePointer = fopen("example.txt", "w");
File modes:
"r"
– Read mode (file must exist)."w"
– Write mode (creates or overwrites a file)."a"
– Append mode (adds data to an existing file)."r+"
, "w+"
, "a+"
– Read and write modes.Use fprintf()
to write formatted text:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(file, "Hello, World!\n");
fclose(file);
return 0;
}
Use fscanf()
to read formatted input:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
char text[100];
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
fscanf(file, "%s", text);
printf("File content: %s\n", text);
fclose(file);
return 0;
}
Use fgets()
for line-by-line reading:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
char line[256];
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(file);
return 0;
}
Use "a"
mode to append text:
FILE *file = fopen("example.txt", "a");
fprintf(file, "Appending text\n");
fclose(file);
Always close a file after use with fclose()
:
fclose(file);
Check if a file was opened successfully:
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
Practice file handling by:
For more advanced file operations, explore binary file handling with fwrite()
and fread()
.