Binary files are very similar to arrays except for the fact that arrays are temporary storage in the memory but binary files are permanent storage in the disks.
The most important difference between binary files and a text file is that in a binary file, you can seek, write, or read from any position inside the file and insert structures directly into the files.
The reasons why binary files are necessary:
1. I/O operations are much faster with binary data.
Usually, large text files contain millions of numbers. It takes a lot of time to convert 32-bit integers to readable characters. This conversion is not required in the case of binary files as data can be directly
stored in the form of bits.
2. Binary files are much smaller in size than text files.
For data that is in the form of images, audio or video, this is very important. Small size means less storage space and faster transmission. For example, a storage device can store a large amount of binary data as compared to data in character format.
3. Some data cannot be converted to character formats.
The basic parameters that the read and write functions of binary files accept are:
- the memory address of the value to be written or read
- the number of bytes to read per block
- the total number of blocks to read
- the file pointer
The functions provided by C libraries are to seek, read, and write to binary files.
The fread() function is used to read a specific number of bytes from the file. An example of fread()
looks like this:
fread(&myRecord, sizeof(struct record), 1, ptr);
This statement reads 'a' bytes (in this case, it's the size of the structure) from the file into the memory address &myRecord. Here the number 1 denotes the number of blocks of 'a' bytes to be read. If we change it to 10, then it denotes 10 blocks of 'a' bytes will be read and stored into &myRecord. ptr is the pointer to the location of the file that is being read.
Now the fwrite() function is used to write to a binary file, like so:
fwrite(&myRecord, sizeof(struct record), 1, ptr);
Getting data using fseek()
If you have many records inside a file and need to access a record at a specific position, you 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);
The first parameter stream is the pointer to the file.
The second parameter is the position of the record to be found, and the third parameter specifies the location where the offset starts.
example:
fseek(fptr, -sizeof(struct threeNum), SEEK_END);
0 comments:
Post a Comment