#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("names.bin","rb+");
//file names.bin 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("names.bin","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;
}