SEEK_SET: 光标在文件的头位置。
SEEK_CUR:当前光标位置。
SEEK_END:光标文件的尾巴位置。
off_t offset : 偏移值。
代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd;
char *buf = "qianrushi";
fd = open("./file1",O_RDWR);
if(fd == -1)
{
printf("open file1 failed\n");
fd = open("./file1",O_RDWR|O_CREAT,0600);
if(fd>0){
printf("create file1 successful\n");
}
}
printf("open success : fd=%d\n",fd);
int n_write = write(fd,buf,strlen(buf));
if(n_write != -1)
{
printf("write %d byte to file\n",n_write);
}
char *readBuf;
readBuf = (char *)malloc(sizeof(char)*n_write+1);
lseek(fd,0,SEEK_SET); //将光标位置从新置于文件头位置
int n_read = read(fd,readBuf,n_write);
printf("read %d,context:%s\n",n_read,readBuf);
close(fd);
return 0;
}