目的:重定向标准输出到一个文件之中。
定义这两个函数的头文件是 unistd.h
这个头文件同时定义了下面三个常量:
* STDIN_FILENO = 0 标准输入
* STDOUT_FILENO = 1 标准输出
* STDERR_FILENO = 2 标准出错输出
dup和dup2函数
#include <unistd.h>
int dup (int filedes);
int dup2 ( int filedes,int filedes2);
两函数的返回值:若成功则返回新的文件描述符,若出错则返回-1
由dup返回的新文件描述符一定是当前可用文件描述符中的最小值。
用dup2则可以用filedes2参数指定新描述符的数值,如果filedes2已经打开,则先将其关闭。如若filedes等于filedes2,则dup2返回diledes2,而不关闭它。
重定向标准输出
实例1:
#include<stdio.h>
#include<unistd.h>
#define TESTSTR "Hello dup2\n"
int main(int argc,char **argv)
{
int fd;
fd =open("testdup2",0666);//打开文件操作
if(fd<0)
{
printf("open error\n");
exit(-1);
}
if(dup2(fd,STDOUT_FILENO) < 0) //括号内把输出重定向到fd标识的文件
{
printf("error in dup2\n");
}
printf("TESTSTR\n");
printf(TESTSTR);
return 0;// close(fd)
} // 显示 TESTSTR
<span style="white-space:pre"> </span>Hello dup2
实例2:制成makefile
dup2_1.c
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#define TESTSTR "Hello dup2\n"
int main(int argc,char **argv)
{
int fd;
if(argc<2)
{
printf("Usage: [file1] [file2] \n",strerror(errno));
exit(1);
}
print(argv[1],TESTSTR);
return 0;
}
print.c
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
void print(const char *filename,const char *str)
{
int fd;
if((fd = open(filename,0666))<0)
{
printf("open erro");
exit(1);
}
dup2(fd, STDOUT_FILENO);
printf("Say = %s",str);
}
print.h
#ifndef _PRINT_H
#define _PRINT_H
void print(const char *filename, const char *str);
#endif
makefile
[songyong@centos6 practice]$ cat makefile
bins=main
objs=dup2_1.o
srcs=dup2_1.c
$(bins):$(objs)
gcc -o main dup2_1.o print.o
$(objs):$(srcs)
gcc -c dup2_1.c
gcc -c print.c print.h
clean:
rm -f $(bins) *.o
测试:
[songyong@centos6 practice]$ ./main
Usage: [file1] [file2]
[songyong@centos6 practice]$ ./main test_1.c
[songyong@centos6 practice]$ cat test_1.c
Say = Hello dup2