I am trying to read in data from a file and am confused. The file contains three columns of data. With fscanf it is giving the correct values.
FILE* fp = fopen("test.txt");
double buffer[3];
fscanf(fp,"%lf %lf %lf",&buffer[0],&buffer[1],&buffer[2]);
Now I am trying to read the same set of values using _read. This gives me all the wrong values.
int fh;
char buffer[50];
_sopen_s( &fh,CStringA(PointFile),_O_RDONLY|_O_BINARY,_SH_DENYNO,0);
_read(fh,buffer,sizeof(double)*3);
It will be really helpful if someone can tell me what I am doing wrong.
The first code snippet reads textual representation of
doubles and converts them. That’s what*scanffamily of functions does.Example valid input:
The second code snippet reads some (probably 24) bytes from a file, without parsing or conversion. You didn’t show how you extract doubles from your buffer. Something like
*(double *)buffer(to get the first value) would be expected, and it would be right (modulo alignment issues, but it’s irrelevant for your platform) if you have a “dump” of 3 platform-specific doubles in your file, created with appropriatefwriteor_write.Example valid input (hex dump, assuming 64-bit IEEE floats):
(If you were using POSIX read, here would be a warning on the possibility of short reads. However,
_readand_s_opensuggest Microsoft CRT, and it doesn’t do short reads in binary mode unless the end of file is reached).