Mode Type Working Description
Mode Type Working Description
rb Open for reading in binary mode. If the file does not exist,
fopen() returns NULL.
ab Open for append in binary mode. If the file does not exist, it
Data is added to the end of the file. will be created.
rb+ Open for both reading and writing in If the file does not exist,
binary mode. fopen() returns NULL.
ab+ Open for both reading and appending If the file does not exist, it
in binary mode. will be created.
Reading and Writing a Binary File
Functions
fread()
and
fwrite()
are used for reading from and writing to a file on
the disk respectively in case of binary files.
Writing to a binary file
To write into a binary file, we need to use
the fwrite() function. The functions take four
arguments:
• address of data to be written in the disk
• size of data to be written in the disk
• number of such type of data
• pointer to the file where you want to write.
Syntax :
fwrite(addressData, sizeData, numbersData, pointerToFile);
Example Writing Binary File
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{ int n1, n2, n3;
};
void main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("program.bin","wb")) == NULL){
printf("Error! opening file");
exit(0); }
for(n = 1; n <= 5; n++) {
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr); } fclose(fptr);
}
Reading from a Binary file
Function fread() also take 4 arguments similar to
the fwrite() function as above.
fread(addressData, sizeData, numbersData,
pointerToFile);
Example Reading Binary File
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{ int n1, n2, n3;
};
void main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("program.bin",“rb")) == NULL){
printf("Error! opening file");
exit(0); }
for(n = 1; n <= 5; n++) {
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
fclose(fptr);
}
Getting data from fseek()
• if we have many records inside a file and need
to access a record at a specific position, we
need to loop through all the records before it
to get the record.
• This will waste a lot of memory and operation
time. An easier way to get to the required
data can be achieved using fseek().
• As the name suggests, fseek() seeks the cursor
to the given record in the file.
Syntax of fseek()
fseek(FILE * stream, long int offset, int whence);