如何解决如何使用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));
解决方法
三件事:
-
请勿链接到代码或错误图片。将错误和源代码一起剪切并粘贴到问题的正文中。
-
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字节的消息
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。