#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>int fd1 , fd2;
int ret;
char buf[128] = {0};int main(void)
{fd1 = open("./test.txt",O_RDWR | O_TRUNC);if (-1 == fd1){perror("open error");return 1;}fd2 = dup(fd1);if (-1 == fd2){/* code */perror("dup error");close(fd1);return 1;}ret = write(fd2,"tammy666",9);if (-1 == ret){/* code */perror("write error");close(fd1);close(fd2);return 1;}lseek(fd2,0,SEEK_SET);//2.在这里使用lseek指针,将读写指针移动到文件头即可,fd1 fd2用的都是一个读写指针,因此将lseek函数指向谁都可以。ret = read(fd2,buf,9);if (-1 == ret){/* code */perror("read error");close(fd1);close(fd2);return 1;}printf("read: %s\n",buf); //1.注意这里read 读取到的是一个空字符串,因为读写指针移到了文件末尾close(fd1);close(fd2);return 0;
}
运行结果: