c - Posix call 'read' does not read entire file -


while programming files stumbled upon strange difference between c library 'fread' function , posix call 'read'; 'read' reads few bytes of file while 'fread' reads whole file. code reads 1024 + 331 bytes, , 'read' returns 0:

char buf[1024]; int id = open("file.ext", 0); int len; while((len = read(id, buf, 1024)) > 0)     println(len); 

while code reads whole file expected, around 11kb:

char buf[1024]; file* fp = fopen("file.ext", "rb"); int len; while((len = fread(buf, 1, 1024, fp)) > 0)     println(len); 

can tell why 'read' doesn't read whole file?

edit2: sorry, using windows mingw, , reading binary file

edit: complete example:

#include <io.h> #include <stdio.h>  int main() {      char buf[1024];     int len;      // loop 1     int id = open("file.ext", 0);     while((len = read(id, buf, 1024)) > 0) {         printf("%d\n", len);     }     close(id);      println("--------");      // loop 2     file* fp = fopen("file.ext", "rb");     while((len = fread(buf, 1, 1024, fp)) > 0) {         printf("%d\n", len);     }     fclose(fp);      while(1) {}      return 0; } 

the output:

1024 331 -------- 1024 1024 1024 1024 1024 1024 1024 1024 1024 1024 981 

you're opening file first time in text mode , second time in binary mode. need open both times in binary mode. if it's not in binary mode, first control-z (hex value 1a) signals "end of file".

add following includes (getting rid of <io.h>):

#include <unistd.h> #include <fcntl.h> 

the call open this:

int id = open("spiderman.torrent", o_rdonly|o_binary); 

here's example of control-z ending file:

#include <stdio.h>  void writeit() {   file *f = fopen("test.txt", "wb");   fprintf(f, "hello world\r\n");   fputc(0x1a, f);   fprintf(f, "goodbye universe\r\n");   fclose(f); }  void readit() {   int c;   file *f = fopen("test.txt", "r");   while ((c = fgetc(f)) != eof)     putchar(c);   fclose(f); }  int main() {   writeit();   readit();   return 0; } 

the above prints "hello world" , not "goodbye universe".


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -