一、写入一个整数到文件
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(){
int fd;
int data = 100;
int data2 = 26;
fd = open("./file1",O_RDWR|O_CREAT|0600);
int n_write = write(fd,&data,sizeof(int));
lseek(fd,0,SEEK_SET);
int n_read = read(fd,&data2,sizeof(int));
printf("read :%d\n",data2);
close(fd);
return 0;
}
二、写入一个结构体数组到文件
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
struct Test{
int a;
char b;
};
int main(){
int fd;
struct Test data[2] = {{100,'c'},{101,'m'}};
struct Test data2[2];
fd = open("./file1",O_RDWR|O_CREAT|0600);
int n_write = write(fd,&data,sizeof(struct Test)*2);
lseek(fd,0,SEEK_SET);
int n_read = read(fd,&data2,sizeof(struct Test)*2);
printf("read :%d,%c\n",data[0].a,data[0].b);
printf("read :%d,%c\n",data[1].a,data[1].b);
close(fd);
return 0;
}