#include <fcntl.h>
open(const char *path, int oflag, ...);
O_RDONLY open for reading only
O_WRONLY open for writing only
O_RDWR open for reading and writing
O_SEARCH open directory for searching
O_EXEC open for execute only
并:
O_APPEND append on each write
O_CREAT create file if it does not exist
O_TRUNC truncate size to 0
O_EXCL error if O_CREAT and the file exists
read
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
read(int fildes, void *buf, size_t nbyte);
write
#include <unistd.h>
write(int fildes, const void *buf, size_t nbyte);
eg:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf="guagua is handsome";
fd=open("./files",O_RDWR);
printf("fd=%d\n",fd);
if(fd==-1){
printf("open files failed\n");
fd=open("./files",O_RDWR|O_CREAT,0600);
if(fd>0)
{
printf("creat files succesed\n");
}
}
printf("open files successed\n");
int n_write=write(fd,buf,strlen(buf));
if(n_write!=-1){
printf("write %d beyt to files\n",n_write);
}
// close(fd);
// fd=open("./files",O_RDWR);
//lseek(int fildes, off_t offset, int whence);
//1 lseek(fd,0,SEEK_SET);
//2 lseek(fd,-n_write,SEEK_END);
lseek(fd,-n_write,SEEK_CUR);
char *readbuf;
readbuf=(char *)malloc(sizeof(char)*n_write);
int n_read=read(fd,readbuf,n_write);
printf("read:%d,context:%s\n",n_read,readbuf);
close(fd);
return 0;
}