I am trying to write binary values in a file using fputc
. In my case it is a short int
.
The file must be opened in "w" mode.
I'm using this function, which is working. I need to know if I'm doing it right or if there are cases that I hadn't anticipated.
void writeListPos(Compressor* comp, short int listPos){
++listPos;
char* posChar = (char*)(&listPos);
int i;
for(i=0 ; i<(sizeof(short int)) ; ++i){
fputc(posChar[i] , comp->outputFile);
}
}
The function to read the file later:
short int readListPos(Compressor* comp){
char* posChar = (char*)(malloc(sizeof(short int)));
int i;
for(i=0 ; i<sizeof(short int) ; ++i){
posChar[i] = comp->lastRead;/* comp->lastRead initialised with a first fgetc*/
comp->lastRead = fgetc(comp->inputFile);
}
short int* positionp = (short int*)posChar;
short int position = (*positionp);
free(posChar);
--position;
return position;
}
short int* positionp = (short int*)posChar;short int position = (*positionp);
3) fwrite & fread is better. – BLUEPIXY May 26 '14 at 16:27comp->lastRead
before callingreadListPos()
for the first time – Ingo Leonhardt May 26 '14 at 16:29