Reputation: 41
I am pretty new to C and like the tittle says I am trying to write a simple program to read and write files in binary. The code is as follows:
#include<stdio.h>
int main(void){
FILE *fd = fopen("binFile.bin", "wb");
if(fd == NULL){
printf("Failed to open/create file.\n");
return -1;
}
char buff1[] = "#This is a comment.\n";
fwrite(buff1,1,sizeof(buff1),fd);
char buff2[] = "#This is another 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 to 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 I run this code it only prints:
#This is a comment.
I know I am not using a bunch of checks for the file; however, I think the problem is that I am trying to read char's and float's with the same buffer since using the same code just for char's (or just float's) works just fine. I am guessing I have to somehow know where the bytes of char's end and the float's begin to adjust my buffer size/type accordingly.
I hope I explain myself sufficiently. Any help is appreciated.
Upvotes: 1
Views: 1537
Reputation:
Take a look at your binary file
As you can see there is a null terminator at byte 14h, just after "This is a comment.\n" string.
This is because you use sizeof(buff1)
on an array of char initialized with a string literal, such literals always include the null terminator.
Also note that you are storing floating point numbers is binary format, if your system use IEEE754 (mine does), when you write -1 is encoded as 0bf800000h
.
This result in having bytes of value 0 in the file, such bytes will be interpreted as null terminators too.
Upvotes: 3