如何使用calloc?

问题描述

注意:用于在服务器上从客户端

接收“数据” 功能

客户代码

void send_file(FILE *fp,int sockfd){

    int size;
    char *buffer;

    while ((fp = fopen("/home/regs_p/cprograms/crypt/RSA.c","r")) != NULL){

        if (fp == NULL) {
            printf("Error opening the file : RSA.c\n");
            exit(EXIT_FAILURE);
        }

        fseek(fp,SEEK_END);
        size = ftell(fp);
        rewind (fp);

        // Allocate a buffer to contain all characters of the file

        buffer = calloc(1,sizeof (char) * (size + 1));

        if (buffer == NULL){
            fprintf(stderr,"Sorry,space is insufficient!");
            exit(EXIT_FAILURE);
        }

        fread(buffer,size,1,fp);

        printf("File size = %d\n",size);
        write(sockfd,buffer,strlen(buffer));

        free(buffer);
        fclose(fp);
    }

    close(sockfd);
    return;
} 

服务器代码

void recv_file(int sockfd){
        
    char *buffer;
    buffer = calloc(1,sizeof (char) * (strlen(sockfd));

    if (buffer == NULL) {
        fprintf(stderr,but you can not insert more articles,the space is insufficient\n");
        exit (EXIT_FAILURE);
    }
         
    printf("Length of the file received has %d characters!",strlen(buffer));

Screenshot of the Error

解决方法

三件事:

  • 请勿链接到代码或错误图片。将错误和源代码一起剪切并粘贴到问题的正文中。

  • strlen期望其参数为char *类型,并且是指向以零结尾的字符串的第一个字符的指针sockfd都不是这些东西。将其从int强制转换为指针类型不会解决任何问题,因为它不是指针 value

  • strlen返回类型为size_t而不是int的值,因此您需要使用%zu转换说明符代替%d打印。

错误缓冲区的长度将需要由套接字文件描述符以外的其他内容确定。您需要将第二个参数传递给recv_file函数:

void recv_file( int sockfd,size_t bufsize )
{
  char *buffer = calloc( bufsize+1,sizeof *buffer );
  if ( !buffer )
    ...
}

否则您将需要依赖一个常量:

#define BUFFER_SIZE 128 // or however long it needs to be
...
void recv_file( int sockfd )
{
  char *buffer = calloc( BUFFER_SIZE+1,sizeof *buffer );
  if ( !buffer )
    ...
}

此时最好将buffer设置为常规数组:

void recv_file( int sockfd )
{
  char buffer[BUFFER_SIZE+1] = {0};
  ...
}

并完全避免内存管理的麻烦。

,

您不能仅通过查看tcp连接来判断文件的长度。您将必须先发送长度,然后发送数据。您将需要继续循环接收。

这是因为tcp是流协议。唯一的保证是您发送的再见按相同的顺序到达。但是您可以发送1个50字节并接收50个1字节的消息