将结构体赋值后写入文件,再用read函数读取到结构体指针中,并没有获取到打印信息,请教这是怎么回事!!
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
struct flow
{
unsigned int num;
char name[32];
unsigned char metric;
};
int main(int argc, const char *argv[])
{
int fd = open("./open.txt",O_RDWR | O_CREAT | O_TRUNC,0666);
if(fd == -1)
{
perror("open failed");
return -1;
}
struct flow t;
memset(&t, 0, sizeof(struct flow));
t.num = 5;
strcpy(t.name, "test");
t.metric = 127;
write(fd, &t, sizeof(struct flow));
struct flow *p = NULL;
p = (struct flow*)malloc(sizeof(struct flow));
printf("ret1: %d\n", ret1);
//读取
int ret1 = lseek (fd, 0, 0);
if (read(fd, p, sizeof(struct flow) == -1))
{
printf("read error\n");
exit(1);
}
//没有打印信息,貌似没有读取成功
printf("==> %d\n", p->num);
printf("==> %s\n", p->name);
printf("==> %d\n", p->metric);
close(fd);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
struct flow
{
unsigned int num;
char name[32];
unsigned char metric;
};
int main(int argc, const char *argv[])
{
FILE *file = fopen("open.bin", "w+b");
if (!file)
{
printf("failed to open file\n");
return -1;
}
struct flow t = {5, "test", 127};
fwrite(&t, sizeof(struct flow), 1, file);
struct flow *p = (struct flow *)malloc(sizeof(struct flow));
rewind(file);
if (fread(p, sizeof(struct flow), 1, file) != 1)
{
printf("read error\n");
return 1;
}
fclose(file);
printf("==> %d\n", p->num);
printf("==> %s\n", p->name);
printf("==> %d\n", p->metric);
return 0;
}
read函数括号写错了,啧啧啧,一个字节也没读