如何将结构体输入到文件
我们的思想是,首先创造一个text
的结构体,其次打开目标文件,如果没有则创建目标文件,之后将结构体内容写入文件。不能忘记使用lseek
将文件光标移动到文件头位置。最后读取文件内容,关闭文件将其打印。
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct text
{
int a;
char c;
};
int main()
{
int fd;
struct text data = {100,'a'};
struct text data2;
fd = open("./file1",O_RDWR|O_CREAT);
int n_write = write(fd,&data,sizeof(struct text));
lseek(fd,0,SEEK_SET);
int n_read = read(fd,&data2,sizeof(struct text));
printf("read %d,%c \n",data2.a,data2.c);
close(fd);
}