#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while (0)
int main(int argc, char *argv[])
{
int fd;
fd = open("test.txt", O_WRONLY | O_CREAT);
if (fd == -1)
ERR_EXIT("open error");
/* close(1);
dup(fd);
*/
dup2(fd, 1);
printf("hello\n");
return 0;
}
注视部分与dup2的函数相同,1默认代表标准的输出,dup是寻找空闲的文件描述符来进行复制,这时fd就指向了标准输出,所以原本输出到控制台的字符“hello”就输出到了test.txt文件中,dup2也是同样的道理。
或者注视掉dup2函数以fcntl函数也可以实现:
close(1);
if( fcntl(fd, F_DUPFD, 0) < 0)
ERR_EXIT("fcntl error");
F_DUPFD表示从指定的起始位置(这里为0)开始搜索可用的文件描述符,dup函数默认从0开始搜索,这就是它们在这里等价的原因。