I am trying to write a C program that reads a binary file and converts it to a data type. I am generating a binary file with a head command head -c 40000 /dev/urandom > data40.bin. The program works for data types int and char but fails for double. Here is the code for the program.
void double_funct(int readFrom, int writeTo){
double buffer[150];
int a = read(readFrom,buffer,sizeof(double));
while(a!=0){
int size = 1;
int c=0;
for(c=0;c<size;c++){
char temp[100];
int x = snprintf(temp,100,"%f ", buffer[c]);
write(writeTo, temp, x);
}
a = read(readFrom,buffer,sizeof(double));
}
}
and this is the char function that works
void char_funct(int readFrom, int writeTo){
char buffer[150];
int a = read(readFrom,buffer,sizeof(char));
while(a!=0){
int size = 1;
int c=0;
for(c=0;c<size;c++){
char temp[100]=" ";
snprintf(temp,100,"%d ", buffer[c]);
write(writeTo, temp, strlen(temp));
}
a = read(readFrom,buffer,sizeof(char));
}
}
The problem is that with char I need to get 40000 words with wc -w file and I get them. Now with double I get random amount of words but theoretically I should get 5000 from 40000 bytes of data but I get a random amount between 4000 and 15000 and for char I get 40000 like it should 1 byte for one character.
I don't know what is wrong the same code works for int where I get 10000 words from 40000 bytes of data.
read()reads the full number of bytes requested. It is essential to use the return value to determine how many bytes actually were read.read()will return-1if an error occurs. You do not account for that possibility, and if an error does occur you process who-knows-what data.int x = snprintf(temp,100,"%f ", buffer[c]);takes a single character from the buffer and tries to convert it to a float. You might want to check the return valuexthat tells you how much was written into the buffer. But, this is certainly not what you want to be doing.write()has similar characteristics toread()with respect to the number of bytes transferred, though in practice that's rarely an issue for local files.doublearray not achararray as in the other version.