Skip to content Skip to sidebar Skip to footer

How to Read a Binary File in C++

In an earlier tutorial we talked about file I/O functions and the use of text files. In this C programming tutorial we are going to talk well-nigh the use of binary files.

Binary files

Binary files are very similar to arrays of structures, except the structures are in a disk-file rather than an array in memory. Binary files accept two features that distinguish them from text files:

  • You can instantly employ any construction in the file.
  • You can modify the contents of a structure anywhere in the file.

After you 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. Afterwards reading the structure the pointer is moved to point at the next structure.

A write operation will write to the currently pointed-to structure. Subsequently the write functioning the file position indicator is moved to indicate at the next structure.

The fseek part volition movement the file position indicator to the record that is requested.

Recall that you keep rails of things, because the file position indicator can non just point at the start of a structure, simply can besides point to any byte in the file.

The fread and fwrite function takes four parameters:

  • A retentivity address
  • Number of bytes to read per block
  • Number of blocks to read
  • A file variable

For instance:

                          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 accost &my_record. Only one cake is requested. Changing the ane into ten will read in ten blocks of x bytes at once.

Let'due south wait at a write instance:

                          #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("examination.bin","wb"); 		if (!ptr_myfile) 		{ 			printf("Unable to open file!"); 			return 1; 		} 		for ( counter=1; counter <= 10; counter++) 		{ 			my_record.10= counter; 			fwrite(&my_record, sizeof(struct rec), ane, 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 main part we open (fopen) a file for writing (w). And so nosotros cheque if the file is open, if not, an error bulletin is displayed and we get out the programme. In the "for loop" we fill the structure member ten with a number. Then nosotros write the record to the file. We practise this ten times, thus creating ten records. After writing the ten records, nosotros will close the file (don't forget this).

And then at present we have written to a file, permit'due south read from the file we have just created. Take a expect at the instance:

                          #include<stdio.h>  	/* Our construction */ 	struct rec 	{ 		int ten,y,z; 	};  	int principal() 	{ 		int counter; 		FILE *ptr_myfile; 		struct rec my_record;  		ptr_myfile=fopen("test.bin","rb"); 		if (!ptr_myfile) 		{ 			printf("Unable to open file!"); 			render 1; 		} 		for ( counter=i; 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 inverse are the two lines in the "for loop". With the fread we read-in the records (one by one). After we accept read the record nosotros impress the member x (of that record).

The simply thing nosotros need to explain is the fseek option. The function fseek must exist declared like this:

                          int fseek(FILE * stream, long int commencement, 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 showtime of the file, is obtained by adding offset to the position specified past whence. 3 macros are declared in stdio.h called: SEEK_SET, SEEK_CUR and SEEK_END.

If the position declared by whence is SEEK_SET, then the position is the beginning of the file.

The SEEK_END tin can exist used if you desire to go to the end of the file. (Using negative numbers it is possible to motion from the terminate of the file.)

If whence is SEEK_CUR then the position is set, x bytes, from the electric current position.

Permit'due south take a look 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("test.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),1,ptr_myfile); 			printf("%d\n",my_record.x); 		} 		fclose(ptr_myfile); 		return 0; 	}                      

In this case we are using fseek to seek the last record in the file. This record nosotros read with fread statement and with the printf statement nosotros print member x of the construction my_record. Every bit you lot can see the "for loop" also changed. The "for loop" will now countdown to zero. This counter is then used in the fseek argument to set the file pointer at the desired record. The result is that we read-in the records in the contrary gild.

A concluding notation: if you fix the file position indicator to a position in a file and y'all desire the first position in a file so y'all tin can use the role rewind to the outset position in the file. The function rewind tin 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 file!"); 			return 1; 		}  		fseek(ptr_myfile, sizeof(struct rec), SEEK_END); 		rewind(ptr_myfile);  		for ( counter=1; counter <= x; counter++) 		{ 			fread(&my_record,sizeof(struct rec),1,ptr_myfile); 			printf("%d\due north",my_record.x); 		} 		fclose(ptr_myfile); 		render 0; 	}                      

With the fseek statement in this example we go to the stop of the file. So nosotros rewind to first position in the file. And so read-in all records and print the value of member x. Without the rewind yous volition go garbage. (Endeavor information technology!)

That is all for this tutorial.

This entry was posted in C Tutorials. Yous tin can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or apply to share this post with others.

cameronwhart1958.blogspot.com

Source: https://www.codingunit.com/c-tutorial-binary-file-io

Post a Comment for "How to Read a Binary File in C++"