File handling in C allows a program to create, open, read, write, append, and close files. Files are useful when data needs to be stored permanently instead of keeping it only in memory while the program is running.
<stdio.h> header file. A file is generally accessed
through a FILE * stream.
File handling means working with files from a C program. A program can use files to store and retrieve data.
Common file operations include:
Variables normally store data only while the program is running. A file can store information so it can be used later.
For example, a student management program can store student information in a file.
File handling functions are available through the standard input/output header file.
#include <stdio.h>
Functions such as fopen(), fclose(),
fprintf(), fscanf(), fgets(),
and fputs() are declared in this header.
C uses a FILE * pointer to work with an opened file stream.
FILE *file;
The pointer is used with functions such as fopen() and
fclose().
The fopen() function opens a file and returns a
FILE * pointer.
FILE *file;
file = fopen("data.txt", "r");
The first argument is the file name and the second argument specifies the opening mode.
The general syntax is:
FILE *fopen(const char *filename, const char *mode);
Example:
FILE *file = fopen("students.txt", "r");
Always check whether the file was opened successfully.
FILE *file = fopen("data.txt", "r");
if(file == NULL)
{
printf("Unable to open file");
}
else
{
printf("File opened successfully");
}
A NULL return indicates that the file could not be opened.
Common text-file opening modes include:
| Mode | Purpose |
|---|---|
"r" |
Open for reading |
"w" |
Open for writing; create or truncate the file |
"a" |
Open for appending; create if necessary |
"r+" |
Open for reading and writing |
"w+" |
Open for reading and writing; create or truncate |
"a+" |
Open for reading and appending; create if necessary |
The "r" mode opens an existing file for reading.
FILE *file = fopen("data.txt", "r");
If the file does not exist, opening with "r" fails.
The "w" mode opens a file for writing.
If the file does not exist, it can be created.
If it already exists, its previous contents are discarded.
FILE *file = fopen("data.txt", "w");
Use this mode carefully when existing data must be preserved.
The "a" mode opens a file for appending.
New data is written at the end of the file.
FILE *file = fopen("data.txt", "a");
Existing contents are preserved.
The fclose() function closes an opened file.
FILE *file = fopen("data.txt", "r");
if(file != NULL)
{
fclose(file);
}
Closing files is an important part of proper file handling.
The fprintf() function writes formatted data to a file.
FILE *file = fopen("data.txt", "w");
if(file != NULL)
{
fprintf(file, "Hello C Programming");
fclose(file);
}
FILE *file = fopen("student.txt", "w");
if(file != NULL)
{
int id = 101;
float marks = 85.5f;
fprintf(file, "ID: %d\n", id);
fprintf(file, "Marks: %.2f\n", marks);
fclose(file);
}
Formatted output can be stored in the file just like output with
printf().
The fscanf() function reads formatted data from a file.
FILE *file = fopen("data.txt", "r");
int number;
if(file != NULL)
{
fscanf(file, "%d", &number);
printf("%d", number);
fclose(file);
}
The fputs() function writes a string to a file.
FILE *file = fopen("message.txt", "w");
if(file != NULL)
{
fputs("Welcome to C Programming", file);
fclose(file);
}
The fgets() function can read a line or part of a line from a
file into a character array.
char line[100];
FILE *file = fopen("message.txt", "r");
if(file != NULL)
{
fgets(line, sizeof line, file);
printf("%s", line);
fclose(file);
}
A loop can be used with fgets() to read a text file line by
line.
char line[100];
FILE *file = fopen("data.txt", "r");
if(file != NULL)
{
while(fgets(line, sizeof line, file) != NULL)
{
printf("%s", line);
}
fclose(file);
}
The fgetc() function reads one character from a file stream.
FILE *file = fopen("data.txt", "r");
if(file != NULL)
{
int ch = fgetc(file);
if(ch != EOF)
{
printf("%c", ch);
}
fclose(file);
}
An int is commonly used to store the result so that the special
value EOF can also be represented.
The EOF indicator can be used to detect the end of a file while
reading characters.
FILE *file = fopen("data.txt", "r");
if(file != NULL)
{
int ch;
while((ch = fgetc(file)) != EOF)
{
putchar(ch);
}
fclose(file);
}
The fputc() function writes a single character to a file.
FILE *file = fopen("data.txt", "w");
if(file != NULL)
{
fputc('A', file);
fputc('B', file);
fputc('C', file);
fclose(file);
}
The file will contain the characters ABC.
Files are commonly handled as text or binary data.
C provides different functions and modes for working with these types of files.
The character b can be added to file modes for binary file
operations.
FILE *file = fopen("data.bin", "rb");
Other examples include "wb" and "ab".
The fwrite() function writes blocks of bytes to a file.
It is commonly used with binary data.
int numbers[3] = {10, 20, 30};
FILE *file = fopen("numbers.bin", "wb");
if(file != NULL)
{
fwrite(numbers, sizeof numbers[0], 3, file);
fclose(file);
}
The fread() function reads blocks of bytes from a file.
int numbers[3];
FILE *file = fopen("numbers.bin", "rb");
if(file != NULL)
{
fread(numbers, sizeof numbers[0], 3, file);
fclose(file);
}
A file stream maintains a current position. The rewind()
function moves the file position back to the beginning of the file.
FILE *file = fopen("data.txt", "r");
if(file != NULL)
{
char line[100];
fgets(line, sizeof line, file);
rewind(file);
fgets(line, sizeof line, file);
fclose(file);
}
#include <stdio.h>
int main()
{
FILE *file;
file = fopen("students.txt", "w");
if(file == NULL)
{
printf("Unable to open file");
return 1;
}
fprintf(file, "Student Management System\n");
fprintf(file, "ID: 101\n");
fprintf(file, "Name: Rahul\n");
fprintf(file, "Marks: 85.50\n");
fclose(file);
printf("Data written successfully");
return 0;
}
#include <stdio.h>
int main()
{
FILE *file;
char line[200];
file = fopen("students.txt", "r");
if(file == NULL)
{
printf("Unable to open file");
return 1;
}
while(fgets(line, sizeof line, file) != NULL)
{
printf("%s", line);
}
fclose(file);
return 0;
}
fopen() returned NULL."w".Create a simple Student Record File Management program.
switch.fopen() call for failure.This project combines file handling with structures, functions, conditions, loops, and formatted input/output.
FILE * is used to work with file streams.fopen() opens a file.fclose() closes a file."r" is used for reading."w" is used for writing and can truncate an existing file."a" is used for appending.fprintf() writes formatted data.fscanf() reads formatted data.fputs() writes strings.fgets() reads strings or lines.fgetc() reads a character.fputc() writes a character.fread() and fwrite() are useful for binary data.Question: Which function is used to open a file in C?