Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

c - system call to populate struct values

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);

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Problem 1:

Where is fd intialized?

Problem 2:

The line

nbytes=write(fd,&m1,sizeof(m1));

write the numerical values of the pointers m1.from and m1.to. It does not write the strings they point to.

If you want to write the contents of m1, you have to serialize the contents of m1.from and m1.to. There are libraries for that purpose. You can see some references from How to serialize data in C.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...