首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

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

2013-02-24 
C语言下的二进制读写的问题本帖最后由 jdwq33 于 2013-02-19 14:19:17 编辑#include stdio.h#include f

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:你的代码真烂

热点排行