C Video Tutorial 12

C Binary File IOWelcome to my C Binary File IO tutorial. With the binary view of a file you have access to all the bytes in the file. You can store strings, arrays, structs, etc.

Aside from showing how to save and retrieve strings, I’ll also cover how to save array data and grab it out of the file randomly. I also briefly cover error handling in C. All the code is available below along with a transcript of what I said for translation.

If you like videos like this it helps to tell Google+ with a click here

Code From the Video

CTutorial12.c

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(void){

	FILE *pFile;
	
	// Holds the data retrieved from the file
	
	char * buffer;
	
	// size_t is a data type used to represent the size
	// of an element in bytes. 10 chars would be equal
	// to a size of 11 for example.
	
	size_t dataInFile;
	
	// Will hold the size of the file
	
	long fileSize;

	// Opens the file using binary mode

	pFile = fopen("names.bin", "rb+");
	
	// If the file doesn't exist we will produce errors
	// and then try to create the file
	
	if(pFile == NULL){
	
		// Prints the string provided followed by the 
		// standard error message and assign an error
		// code to the variable errno
	
		perror("Error Occurred");
		printf("Error Code: %d\n", errno);
		
		printf("File Being Created\n\n");
		
		// Create the file
		
		pFile = fopen("names.bin", "wb+");
		
		if(pFile == NULL){
		
			perror("Error Occurred");
			printf("Error Code: %d\n", errno);
			exit(1);
		
		}
	
	}

	char name[] = "Derek Banas";

	// fwrite() writes binary data to a file
	// You pass a pointer to what to write to the file. 
	// Then the size of each element in the array for example,
	// or if you are righting a struct sizeof(theStruct).
	// The 3rd is the number of elements to write of the type
	// specified. Finally list the file pointer

	fwrite(name, sizeof(name[0]), sizeof(name)/sizeof(name[0]), pFile);
	
	// Go to the end of the file with fseek(), so I can use
	// ftell() to get the file size
	
	fseek (pFile , 0 , SEEK_END);
    fileSize = ftell(pFile);
    
    // Set pointer back to the beginning of the file
    
    rewind(pFile);
    
    // Set aside enough space in memory to hold the file
    
    buffer = (char*) malloc (sizeof(char)*fileSize);
    
    if(buffer == NULL){
    
    	perror("Error Occurred");
		printf("Error Code: %d\n", errno);
    	exit(2);
    
    }
    
    // fread() reads data from the file provided into the 
    // buffer provided. The 2nd attribute is the number
    // of bytes taken up by each element read. The 3rd
    // attribute is the number of elements to read.
    
    // fread() returns a size_t equal to the amount of
    // bytes stored in the file.
    
    dataInFile = fread(buffer, 1, fileSize, pFile);
    
    if(dataInFile != fileSize){
    
    	perror("Error Occurred");
		printf("Error Code: %d\n", errno);
    	exit(3);
    
    }
	
	printf("%s\n", buffer);
	
	printf("\n");
	
	// Closes the file associated with the stream
	
	fclose(pFile);
	
	// Deallocates the memory block created for the buffer
	
	free(buffer);

	return 0;
}

CTutorial12_2.c

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(void){

	FILE *pFile;
	size_t dataInFile;

	// Opens the file using binary mode
	pFile = fopen("randomnums.bin", "rb+");
	
	if(pFile == NULL){
	
		perror("Error Occurred");
		printf("Error Code: %d\n", errno);
		printf("File Being Created\n\n");
		
		pFile = fopen("randomnums.bin", "wb+");
		
		if(pFile == NULL){
		
			perror("Error Occurred");
			printf("Error Code: %d\n", errno);
			exit(1);
		
		}
	}
	
	// NEW STUFF ----------
	
	int randomNumbers[20];
	
	for(int i = 0; i < 20; i++){
	
		randomNumbers[i] = rand() % 100;
		
		printf("Number %d is %d\n", i, randomNumbers[i]);
	
	}
	
	// Write the array of ints to the file

	fwrite(randomNumbers, sizeof(int),
	 	20, pFile);
	
	long randomIndexNumber;
	int numberAtIndex;
	
	printf("Which Random Number do you Want? ");
	
	scanf("%ld", &randomIndexNumber);
	
	// When using fseek() in binary mode make sure the
	// offset is the number of the element * possible size 
	
	fseek(pFile, randomIndexNumber * sizeof(int), SEEK_SET);
	
	// Read the next int from the file
	
	fread(&numberAtIndex, sizeof(int), 1, pFile);
	
	printf("The Random Number at Index %d is %d\n",
		randomIndexNumber, numberAtIndex);
	
	// END OF NEW STUFF	
	
	// Closes the file associated with the stream
	
	fclose(pFile);

	return 0;
}

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Google+