1.函数功能
int dup (int oldfd); 复制一个已经存在的文件描述符
2.程序源码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
char *buf1 = "hello";
char *buf2 = " world\n";
int fd = open("a.txt", O_RDWR|O_CREAT);
int ret = 0;
if(fd < 0)
{
perror("open");
exit(-1);
}
printf("file open fd=%d\n", fd);
ret = dup(fd);
if(ret < 0)
{
perror("dup");
exit(-1);
}
printf("file dup ret=%d\n", ret);
write(fd, buf1, strlen(buf1));
write(ret, buf2, strlen(buf2));
return 0;
}
4.编译源码
$ gcc -o dup dup.c
5.运行程序
$ ./dup
file open fd=3
file dup ret=4
6.查看文件数据
$ cat a.txt
hello world
网友评论