if I read file by calling read() like this:
unsigned char buf[512];
memset(buf, 0, sizeof(unsigned char) * 512);
int fd;
int readcount;
int offset = 10315001; /* file size is 14315504 */
fd = open("myfile", O_RDONLY);
lseek(fd, offset, SEEK_SET);
readcount = read(fd, (void*)buf, 8);
close(fd);
the read() returns 0, but the memory of “buf” has been changed(not 0 any more). And if I tried to read the same offset and same file with fread() like this:
FILE* file;
file = fopen("myfile", "r");
fseek(file, offset, SEEK_SET);
readcount = fread((void*)buf, 8, 1, file);
fclose(file);
fread() returns 0 either, but the buf is as same as before.
if read() failed, why it changes the memory space of “buf”? Or did I make some mistakes?
Thanks for help : )
Edit: Every time I ran the code above, the “buf” changed by read() in the same way -> from 0 to the same values. So the changed “buf” may not be random values?
Edit 2: The offset parameter is valid(thanks twalberg), and if I read another valid offset, both read() and fread() will be succeeded and the result of “buf” is the same. Is there any way to find what’s wrong when read() failed? The errno is “No errors” when read() returns 0.
I think I’ve found what’s going on here.
The file is a binary one, but I read() it with text mode(O_RDONLY).
The value of offset 10315001 is 0x1a, when read() and fread() function meets 0x1a in text mode, they both will return 0, but the different is, the read() will still write the buf with binary mode, while fread() won’t do this.