复制一个现存的文件的描述
函数名称:dup dup2
函数原型:
int dup(int fd);
int dup2(int fd1,int fd2);
函数功能:复制一个现存的文件的描述
返回值:若成功为新的文件描述,若出错为-1;
由dup返回的新文件描述符一定是当前可用文件描述中的最小数值。用dup2则可以用fd2参数指定新的描述符数值。如果fd2已经打开,则先关闭。若fd1=fd2,则
dup2
返回fd2,而不关闭它。通常使用这两个系统调用来重定向一个打开的
文件描述符
。
demo:把hello打印到test2.txt中
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int main(int argc, char *argv[])
{
int fd;
fd = open("test2.txt", O_WRONLY);
if (fd == -1)
ERR_EXIT("open error");
/*
close(1);
dup(fd);
*/
dup2(fd, 1);
printf("hello\n");
return 0;
}
函数名称:fcntl
函数原型:int fcntl(int fd, int cmd, long arg);
函数功能:复制一个现存的文件的描述
返回值:若成功为新的文件描述,若出错为-1;
#include <sys/types.h> /*for open*/
#include <sys/stat.h> /*for open*/
#include <fcntl.h> /*for open fcntl*/
#include <stdlib.h> /*for perror exit*/
#include <stdio.h> /*for perror*/
#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);
if (fd == -1)
ERR_EXIT("open error");
close(1);
if (fcntl(fd, F_DUPFD, 0) < 0)
ERR_EXIT("dup fd error");
printf("-----------\n");//进行重定向,将不会显示在标准输出,
return 0;
}