write() not writing correct amout of bytes on windows in C
Domanda
When writing values to a file in C under Windows, I'm getting something which seems to be wrong, and the result differs from the same program run in Cygwin.
In this case, I'm writing a float to a file:
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
int main( void )
{
int fd;
float f;
fd = open("file.a", O_RDWR | O_CREAT);
f = (float)atof("-0.1352237");
printf("%.7f\n", f);
write(fd, (void *)&f, sizeof(float));
close(fd);
printf("sizeof(float): %d\n", sizeof(float));
return (EXIT_SUCCESS);
}
I've compiled and run this file on both Windows and in Cygwin (without the include), and I'm not getting the same result. Since I'm writing a float, I would expect the output file to have 4 bytes written to it
However, the output when compiled with cl.exe in the command line, seems wrong:
1578 0d0a be
If I read from the file to a float, I'm not getting the correct value, obviously. And the amount of bytes written to the file is wrong to, it should only be 4 bytes, not 5.
This is what I get when running in Cygwin:
1578 0abe
This is correct. If I read this from the file to a float I get the correct value (-0.1352237).
Am I missing something here ? Are the windows implementation of those functions flawed ? Or maybe I'm not writing the data properly ?
Soluzione
You have opened the file in text mode (the default), so the 0a
("\n"
) is being translated to 0d0a
("\r\n"
).
You need to open the file in binary mode, using the O_BINARY
flag.