我正在尝试使用wget下载文件,然后将其打开,将其读入缓冲区,然后通过套接字将其发送到等待它的服务器。我已成功下载该文件然后打开它,但当我尝试将其读入缓冲区时出现问题。我正在尝试下载的文件长度为8000字节但是当我将其写入缓冲区然后运行sizeof(fileBuffer)时,它只报告8字节的大小。这是代码:
//open the file
if((downloadedFile = fopen(fileName, "rb"))==NULL){
perror("Downloaded file open");
}
//determine file size
fseek(downloadedFile, 0L, SEEK_END);
downloadedFileSize = ftell(downloadedFile);
fseek(downloadedFile, 0L, SEEK_SET);
printf("%s %d \n", "downloadedFileSizse = ",downloadedFileSize);
//send back length of file
if (send(acceptDescriptor, &downloadedFileSize, sizeof(long), 0) == -1){
perror("send downloaded file size Length");
exit(0);
}
//start by loading file into the buffer
char *fileBuffer = malloc(sizeof(char)*downloadedFileSize);
int bytesRead = fread(fileBuffer,sizeof(char), downloadedFileSize, downloadedFile);
printf("%s %d \n","bytesRead: ", bytesRead);
printf("sizeof(fileBuffer) Send back to SS: %d\n",sizeof(fileBuffer));
这是我得到的输出:
HTTP request sent, awaiting response... 200 OK
Length: 8907 (8.7K) [text/html]
Saving to: âindex.htmlâ
100%[======================================>] 8,907 --.-K/s in 0s
2013-10-13 09:35:16 (158 MB/s) - âindex.htmlâ saved [8907/8907]
downloadedFileSizse = 8907
bytesRead: 8907
sizeof(fileBuffer) Send back to SS: 8
bytesLeft: 0
n: 8907
当我运行fread时,它正在读取8907个字节但由于某种原因它没有正确地将它们写入缓冲区。
答案 0 :(得分:2)
fileBuffer
是一个字符指针,因此sizeof
将报告字符指针的大小,而不是缓冲区的大小。 fread
的返回值是写入缓冲区的字节数,因此请使用bytesRead
作为缓冲区的大小。