strcpy和memcpy主要的区别。
复制的内容不同。strcpy只能复制字符串,而memcpy可以复制任意内容,例如字符数组、整型、结构体、类等。
因此在传输此结构体时,我们采用memcpy先将结构体转换为字符串。
传输端:
struct student
{
char name[20];
int num;
};
while(1)
{
struct student student1;
memset(&student1,0,sizeof(student1));
scanf("%s",&student1.name);
scanf("%d",&student1.num);
memcpy(s,&student1,sizeof(student1));
if( write(sockfd, s, sizeof(s)) < 0)
{
printf("send message error: %s(errno: %d)\n", strerror(errno), errno);
exit(0);
}
}
接收端:
struct student
{
char name[20];
int num;
};
while(1)
{
struct student p2;
n=read(confd,recvline,MAXLINE);
recvline[n]='\0';
memset(&p2,0,sizeof(p2));
memcpy(&p2,recvline,sizeof(p2));
printf("%s\n",p2.name);
printf("%d\n",p2.num);
}