i pretty new c , tittle says trying write simple program read , write files in binary. code follows:
#include<stdio.h> int main(void){ file *fd = fopen("binfile.bin", "wb"); if(fd == null){ printf("failed open/create file.\n"); return -1; } char buff1[] = "#this comment.\n"; fwrite(buff1,1,sizeof(buff1),fd); char buff2[] = "#this comment.\n"; fwrite(buff2,1,sizeof(buff2),fd); int i; float f[3]; for(i=0; i<100; i++){ f[0] = i-1; f[1] = i; f[2] = i+1; fwrite(f,sizeof(f),1,fd); } fclose(fd); fd = fopen("binfile.bin", "rb"); if(fd == null){ printf("failed read file.\n"); return -1; } char buff[100]; do{ fread(buff,1,sizeof(buff),fd); printf("%s",buff); } while(!feof(fd)); fclose(fd); return 0; } when run code prints:
#this comment. i know not using bunch of checks file; however, think problem trying read char's , float's same buffer since using same code char's (or float's) works fine. guessing have somehow know bytes of char's end , float's begin adjust buffer size/type accordingly.
i hope explain myself sufficiently. appreciated.
take @ binary file

as can see there null terminator @ byte 14h, after "this comment.\n" string.
this because use sizeof(buff1) on array of char initialized string literal, such literals always include null terminator.
also note storing floating point numbers binary format, if system use ieee754 (mine does), when write -1 encoded 0bf800000h.
result in having bytes of value 0 in file, such bytes interpreted null terminators too.
Comments
Post a Comment