我正在尝试通过 UDP 套接字发送文件(一次一个块)。它适用于 .txt 文件,但是当我尝试从 .jpg/.rar 读取时,即使文件 >2mb ,它也只能读取几个字节(比我“要求”的要少)。
我尝试使用 open/pread(我也尝试使用 lseek 和 read)和 fopen(在二进制模式下)/fread/fseek,我得到了相同的结果(即对于 2mb .jpg 文件,我得到这个输出“从偏移量读取 10 0”)。请告诉我我做错了什么。
这是负责从文件中读取块的代码:
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);
...
}