系统调用填充结构值 [英] system call to populate struct values

查看:96
本文介绍了系统调用填充结构值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用填充系统调用结构值。我最初的工作如下。但是我从打印语句垃圾值。

I'm trying to populate struct values using system calls. My initial effort follows. However i get junk values from the print statement.

int fd;
int nbytes;
struct message {
  char *from;
  char *to;
  int size;
};
struct message m1={"me","you",10};
struct message m2;

fd=creat("structfile",0644);
nbytes=write(fd,&m1,sizeof(m1));
read(fd,&m2,nbytes);

printf("%s %s %d",m2.from,m2.to,m2.size);

有另一种方式来做到这一点? (我想的方式,结构如 hostent 的dirent 直接通过调用<$填补C $ C>的gethostbyname 和 READDIR 分别)

Is there another way to do this? (I'm thinking of the way that structures like hostent and dirent are filled up directly by making calls to gethostbyname and readdir respectively)

推荐答案

问题3 ,你的结构包含字符指针:

Problem 3, your struct contains character pointers:

struct message {
  char *from;
  char *to;
  int size;
};

的sizeof(M1)写入 2(字符*)指针一(INT)。这些数据指出,由可以基于字符串的大小。读的sizeof(M1)不考虑字符串的大小指出。

Your sizeof(m1) writes the size of 2 (char *) pointers and an (int). The data pointed to by from and to can vary based on the size of the string. Reading sizeof(m1) does not take into account the size of the strings pointed to.

这篇关于系统调用填充结构值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆