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 に答える