读书人

C语言上的二进制读写的有关问题

发布时间: 2013-02-24 17:58:56 作者: rapoo

C语言下的二进制读写的问题
本帖最后由 jdwq33 于 2013-02-19 14:19:17 编辑 #include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
char name[4];
int age;
}people;

int main(int argc, char** argv)
{
people* he;
int fd, i = 0;

#if 1
fd = open("test_h", O_CREAT | O_RDWR | O_APPEND);
he = (people*)malloc(sizeof(people));

for(i=0; i<10; i++)
{
sprintf(he->name, "%c", 'a' + i);
he->age = i;

write(fd, he, sizeof(he));
}

close(fd);
#endif

#if 1

fd = open("test_h", O_RDONLY);
for(i=0; i<10; i++)
{
read(fd, he, sizeof(he));
//he->age为什么读出不是1到9呢?
printf("%s, %d\n", he->name, he->age);
}
#endif
close(fd);
free(he);

return 0;
}
c struct read???write
[解决办法]
sizeof(he)
改为
sizeof(*he)

BTW:你的代码真烂

读书人网 >C语言

热点推荐