在C中成功发送和接收文件大小

问题描述

我希望能够从客户端向服务器发送文件。我正在使用TCP。我试图使用fseek等获取文件的大小,因为我希望能够处理大文件,然后将一定数量的数据以及文件内容发送到服务器。到目前为止,根据我的printf消息,一切都通过并创建了文件。但是,在服务器上创建的文件为空。我通过参数等发送和接收消息的方式显然存在问题,但我无法弄清楚。有人可以告诉我我哪里出了问题以及如何修复它,因为我是如此接近!

服务器部分:

if(getFile){
         
                char *tmp = buf + 9;
                char filename2[MAX_BLOCK_SIZE];
                int length,x;
                long file_size = 0;
                FILE *fp;
                strcpy(filename2,tmp);
                printf("Server receiving file name...\n");
                //first 'read' receives the file name
                fp = fopen(filename2,"wb");
                if(fp == NULL){
                    printf("File Could not be opened.\n");
                    exit(1);
                }
                printf("Server receiving file...\n");
                while((x = read(sd,buf,sizeof(buf)) > 0)){ //second read Now retrieving the file
                    printf("Server creating new file...\n");
                    fwrite(buf,1,file_size,fp);
                }
            fclose(fp);
            printf("The server has received the requested document.\n");
         }

客户端:

 else if(putCommand){
            
            char *tmp = buf + 4;
            char filename[MAX_BLOCK_SIZE];
    
        long file_size;
            strcpy(filename,"filename ");
            strcat(filename,tmp);
            FILE *fp;
            printf("File name: %s\n",tmp);
            fp = fopen(tmp,"rb");
            if(fp == NULL){
                
                printf("ERROR: Requested file does not exist.\n");
                
            }
            else{
            printf("Client sending filename...\n");
            if ((nw = write(sd,filename,sizeof(filename)) < nr)){     //sending the file name to the client first
                printf("Error sending client's filename.\n");
            }
            
            //size_t file_size;
            printf("Client sending file...\n");
            fseek(fp,SEEK_END);
            long filesize = ftell(fp);
            fseek(fp,SEEK_SET);
            
            while((file_size = fread(buf,MAX_BLOCK_SIZE,fp)) > 0){ //sending the file
            
                if ((x = write(sd,filesize) < 0)){
                    printf("Error sending client file.\n");
                }
            
            }
            fclose(fp);
            
            
            }

解决方法

这是一个错字。在接收方,您有:

long file_size = 0;
...
    while(...)
        ...
        fwrite(buf,1,file_size,fp);

所以您始终写入0字节。

标准方法是:

    while((x = read(sd,buf,sizeof(buf)) > 0)){ //second read now retrieving the file
        printf("Server creating new file...\n");
        fwrite(buf,x,fp);     // write the number of bytes returned by previous read
    }

最后,我希望buf是一个真实的数组,而不是一个指针...