#include<stdio.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<unistd.h>#include<stdlib.h>intmain(){
int fd;char buf[]="xxxxxxxxxxxxxxxxxxxxx";int data=100;
fd=open("./file1",O_RDWR);if(fd==-1)//如果没有则创建{
printf("fail to open this file1!!!\n");
fd=open("./file1",O_RDWR|O_CREAT,0600);{
printf("successful creat file1!!n");}}printf("open success fd=%d!!!!\n",fd);int num_write=write(fd,&data,sizeof(data));//返回写入到字符个数if(num_write!=-1){
printf("write success!!!\n");}close(fd);//关闭当前文档
fd=open("./file1",O_RDWR);//重新打开该文档,光标定位开头int*readBuf;
readBuf=(int*)malloc(sizeof(int)*num_write+1);int num_read=read(fd,readBuf,num_write);printf("read:%d\n",*readBuf);close(fd);return0;}
2.结构体数组的写入
#include<stdio.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<unistd.h>#include<stdlib.h>structName{
char N;int data;};intmain(){
int fd;char buf[]="xxxxxxxxxxxxxxxxxxxxx";int data=100;structName Ren[2]={
{
'a',100},{
'b',200}};structName RenRead[2];
fd=open("./file1",O_RDWR);if(fd==-1)//如果没有则创建{
printf("fail to open this file1!!!\n");
fd=open("./file1",O_RDWR|O_CREAT,0600);{
printf("successful creat file1!!n");}}printf("open success fd=%d!!!!\n",fd);int num_write=write(fd,&Ren,sizeof(Ren));//返回写入到字符个数if(num_write!=-1){
printf("write success!!!\n");}close(fd);//关闭当前文档
fd=open("./file1",O_RDWR);//重新打开该文档,光标定位开头int num_read=read(fd,RenRead,num_write);printf("read:%c\n",RenRead[0].N);printf("read:%d\n",RenRead[0].data);close(fd);return0;}