0

我正在尝试使用 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 个字节,但由于某种原因,它没有正确地将它们写入缓冲区。

4

1 回答 1

2

fileBuffer是一个字符指针,所以sizeof会报告字符指针的大小,而不是缓冲区的大小。的返回值fread是写入缓冲区的字节数,因此bytesRead用于缓冲区的大小。

于 2013-10-13T15:49:14.100 回答