How do I read from a non-text file in c (linux)?

c, linux

Solution

A binary file can contain `NULL`-bytes, `strlen` will stop counting after finding such a `NULL`-byte. Use the return-value of `pread` to find out the size of the `buff`er.

All `str`* functions expect C-strings, which must end with a `NULL`-byte and cannot have them 'in the middle'.

Problem

I'm trying to send files(one chunk at a time) through a UDP socket. It works fine for .txt files but when I try to read from .jpg/.rar it reads only a few bytes(less than I "ask" for) even though the files are >2mb . I tried using both open/pread(i also tried using lseek and read) and fopen(in binary mode)/fread/fseek and I get the same result(i.e. for a 2mb .jpg file i get this output "read 10 from offset 0"). Please tell me what am I doing wrong. this is the code responsible for reading a chunk from a file: ``` void * work(void * p){ ... int psize=100; int file; //FILE *file; //open the file file=open(wArg.req.fileName, O_RDONLY); //file=fopen(wArg.req.fileName, "rb"); //read the file chunk from the offset buff=(void *) malloc(psize); n=pread(file, buff, psize, wArg.req.offset); //fseek(file,wArg.req.offset, SEEK_SET); //fread(buff, 1, psize, file); if(n<0){ perror("read"); exit(1); } printf("read %d from offset %d\n", (int)strlen(buff),wArg.req.offset); n=sendto(wArg.sock, buff, psize, 0, (struct sockaddr*)&caddr, sizeof(struct sockaddr_in)); printf("sent %d\n", (int)strlen(buff)); close(file); //fclose(file); ... } ```

Original source