3

我正在尝试通过 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);
...
}
4

3 回答 3

4

二进制文件可以包含NULL-bytes,strlen找到这样的 -byte 后将停止计数NULL。使用的返回值pread找出buffer 的大小。

所有str* 函数都需要 C 字符串,它必须以-byte结尾NULL并且不能将它们放在“中间”。

于 2013-04-16T20:24:56.587 回答
2

你不能拿strlen (buff),因为buff是二进制数据。当您这样做pread时,您捕获的返回值n包含读取的字节数。您应该使用它而不是psizein sendto

于 2013-04-16T20:25:00.633 回答
0

pread() 从文件描述符文件中偏移偏移量(从文件开头)读取最多 count 个字节到缓冲区中,从 buf 开始。文件偏移量没有改变。由于它是一个二进制文件,所以 strlen 不能在这里工作......所以使用 pread 并初始化 psize 以返回 pread() 的值。

于 2013-04-17T08:47:00.173 回答