Chapter 10
File Management in C

A File can be used to store a large volume of persistent data. Like many other languages ‘C’ provides following file management functions
- Creation of a file
- Opening a file
- Reading a file
- Writing to a file
- Closing a file
File pointer
Any “file” is a structure which needs to be created for opening the file.
A file pointer is a pointer to this structure of the file.
A file pointer can be created as follows :
File *ptr;
ptr = fopen("file name.txt","mode");
// Any type of file you can choose like txt ext others
File opening mode in C
C offer the programmer to select a mode for opening a file. Following modes are primarily used in C file management
"r" open for Reading
"rb" open for Reading in binary file
"w" open for Writing
"wb" open for Writing in binary
"a" open for append
Types of File
There are two types of files
- Text file (.txt, c)
- Binary files (.jpg,. dat)
Reading a file
A file can be opened for reading as follows
File *ptr;
ptr = fopen ("hytek.txt","r");
int num;
Let us assume that “hytek.txt” contains an integer we can read that integer using
fscanf(ptr,"%d",&num);
This will read an integer from file in num variable
Closing the File
It is very important to close the file after read or write this is achieved using fclose as follows : fclose (ptr);
This will tell the compiler that we are done working with this file and the associated resources could be free
Writing to a file
We can write to a file in a very similar manner like we read the file
file *fptr;
fptr = fopen ("hytek.txt","w");
int num = 578;
fprintf(fptr, "%d",num);
fclose (fptr);
fgetc( ) and fputc( )
fgetc & fputc are used to read and write a character from to a file
fgetc (ptr);
fputc ('c',ptr);
End of File (EOF)
fgetc returns EOF when all the characters from a file have been read so we can write a cheque like below to detect end of file.
#include <stdio.h>
int main() {
FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
putchar(c);
c = getc(f);
}
fclose(f);
getchar();
return 0;
}