How to Open and Read File C++ in Binary
In an earlier tutorial we talked about file I/O functions and the employ of text files. In this C programming tutorial we are going to talk near the use of binary files.
Binary files
Binary files are very similar to arrays of structures, except the structures are in a deejay-file rather than an array in memory. Binary files have two features that distinguish them from text files:
- You tin instantly use whatever structure in the file.
- You can change the contents of a construction anywhere in the file.
After you lot have opened the binary file, you can read and write a structure or seek a specific position in the file. A file position indicator points to record 0 when the file is opened.
A read operation reads the structure where the file position indicator is pointing to. Later on reading the construction the pointer is moved to point at the next structure.
A write functioning will write to the currently pointed-to structure. Afterwards the write operation the file position indicator is moved to point at the next structure.
The fseek role will motility the file position indicator to the tape that is requested.
Remember that you keep track of things, considering the file position indicator tin non only point at the kickoff of a structure, but tin likewise point to whatsoever byte in the file.
The fread and fwrite function takes four parameters:
- A retentiveness address
- Number of bytes to read per cake
- Number of blocks to read
- A file variable
For example:
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
This fread statement says to read x bytes (size of rec) from the file ptr_myfile into memory address &my_record. Merely one block is requested. Irresolute the one into ten will read in 10 blocks of x bytes at in one case.
Let'southward look at a write example:
#include<stdio.h> /* Our structure */ struct rec { int x,y,z; }; int main() { int counter; FILE *ptr_myfile; struct rec my_record; ptr_myfile=fopen("examination.bin","wb"); if (!ptr_myfile) { printf("Unable to open file!"); return i; } for ( counter=ane; counter <= 10; counter++) { my_record.x= counter; fwrite(&my_record, sizeof(struct rec), 1, ptr_myfile); } fclose(ptr_myfile); render 0; }
In this example we declare a structure rec with the members x,y and z of the type integer. In the chief function we open up (fopen) a file for writing (w). And so we check if the file is open, if not, an mistake message is displayed and nosotros exit the program. In the "for loop" we fill the structure member ten with a number. So we write the record to the file. Nosotros do this 10 times, thus creating ten records. After writing the ten records, nosotros will close the file (don't forget this).
So now we have written to a file, let'south read from the file we have just created. Accept a look at the example:
#include<stdio.h> /* Our structure */ struct rec { int x,y,z; }; int main() { int counter; FILE *ptr_myfile; struct rec my_record; ptr_myfile=fopen("examination.bin","rb"); if (!ptr_myfile) { printf("Unable to open file!"); return i; } for ( counter=ane; counter <= x; counter++) { fread(&my_record,sizeof(struct rec),1,ptr_myfile); printf("%d\n",my_record.x); } fclose(ptr_myfile); return 0; }
The only two lines that are changed are the ii lines in the "for loop". With the fread we read-in the records (one by 1). After we have read the record we impress the fellow member x (of that record).
The only thing we need to explain is the fseek option. The part fseek must be declared like this:
int fseek(FILE * stream, long int offset, int whence);
The fseek function sets the file position indicator for the stream pointed to by the stream. The new position, measured in characters from the first of the file, is obtained by adding offset to the position specified by whence. Three macros are declared in stdio.h chosen: SEEK_SET, SEEK_CUR and SEEK_END.
If the position declared by whence is SEEK_SET, so the position is the commencement of the file.
The SEEK_END tin be used if you desire to get to the end of the file. (Using negative numbers it is possible to move from the end of the file.)
If whence is SEEK_CUR then the position is set, x bytes, from the electric current position.
Let's take a wait at an example:
#include<stdio.h> /* Our structure */ struct rec { int x,y,z; }; int chief() { int counter; FILE *ptr_myfile; struct rec my_record; ptr_myfile=fopen("examination.bin","rb"); if (!ptr_myfile) { printf("Unable to open file!"); render i; } for ( counter=9; counter >= 0; counter--) { fseek(ptr_myfile,sizeof(struct rec)*counter,SEEK_SET); fread(&my_record,sizeof(struct rec),i,ptr_myfile); printf("%d\northward",my_record.x); } fclose(ptr_myfile); return 0; }
In this example we are using fseek to seek the terminal record in the file. This record we read with fread argument and with the printf statement we impress fellow member 10 of the structure my_record. As you tin come across the "for loop" also changed. The "for loop" volition now countdown to nada. This counter is then used in the fseek statement to gear up the file pointer at the desired record. The result is that we read-in the records in the reverse order.
A last notation: if yous fix the file position indicator to a position in a file and y'all desire the first position in a file so yous can utilise the function rewind to the first position in the file. The function rewind can be used like this:
#include<stdio.h> /* Our construction */ struct rec { int x,y,z; }; int main() { int counter; FILE *ptr_myfile; struct rec my_record; ptr_myfile=fopen("test.bin","rb"); if (!ptr_myfile) { printf("Unable to open up file!"); render 1; } fseek(ptr_myfile, sizeof(struct rec), SEEK_END); rewind(ptr_myfile); for ( counter=1; counter <= 10; counter++) { fread(&my_record,sizeof(struct rec),ane,ptr_myfile); printf("%d\northward",my_record.x); } fclose(ptr_myfile); return 0; }
With the fseek statement in this example we go to the end of the file. Then we rewind to first position in the file. Then read-in all records and impress the value of member 10. Without the rewind y'all will get garbage. (Try it!)
That is all for this tutorial.
This entry was posted in C Tutorials. You lot can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently airtight. Tweet This! or utilise to share this postal service with others.
Source: https://www.codingunit.com/c-tutorial-binary-file-io
0 Response to "How to Open and Read File C++ in Binary"
إرسال تعليق