0% found this document useful (0 votes)
90 views2 pages

Example Binary File Error Handling

The document discusses opening, reading, and writing to binary files in C. It demonstrates opening a file, writing data to it, getting the file size, rewinding the file pointer, reading the data into a buffer, and closing the file.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views2 pages

Example Binary File Error Handling

The document discusses opening, reading, and writing to binary files in C. It demonstrates opening a file, writing data to it, getting the file size, rewinding the file pointer, reading the data into a buffer, and closing the file.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#include <stdio.

h> //scanf , printf

#include <stdlib.h>//needed for exit(0)


#include <string.h>

#include <errno.h>//error library


//compile with gcc -std=c99 filename.c
//compile with newer c standart gcc -std=c11 filename.c

int main(){

FILE *pFile;

char *buffer;

//size of elemnt in bytes


size_t dataInFile;

long fileSize;

// b is for binary
pFile =fopen("[Link]","rb+");

//file [Link] does not exist so we will catch the error

if(pFile==NULL){

perror("Error Occured");
printf("Error Code: %d\n",errno);

printf("File Being Created\n");


pFile =fopen("[Link]","wb+");

if(pFile==NULL){

perror("Error Occured");
printf("Error Code: %d\n",errno);
exit(1);//terminate program if continous error
}
}

//file creation or open succcess

char name[]="kestas mtk";

//write binary data


//pass in inout data, size of single element, number of elements
fwrite(name,sizeof(name[0]),sizeof(name)/sizeof(name[0]),pFile);

//lets get file size


//move cursot to end

fseek(pFile,0,SEEK_END);
fileSize=ftell(pFile);

//move cursor to front also with rewind()


rewind(pFile);

buffer=(char*)malloc(sizeof(char)*fileSize);

if (buffer==NULL)
{
perror("Error Occured");
printf("Error Code: %d\n",errno);
exit(2);//terminate program
}

//read from binary file to buffer


//pass in buffer to read to,
//number of bytes taken by each element,
//number of elemnts
//file
dataInFile=fread(buffer,sizeof(char),fileSize,pFile);

if (dataInFile!=fileSize)
{
perror("Error Occured");
printf("Error Code: %d\n",errno);
exit(3);//terminate program
}

//no error occured print buffer


printf("%s\n",buffer);
printf("\n");

fclose(pFile);
//deallocate buffer memory
free(buffer);

return 0;
}

You might also like