专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > 编程

APUE之dup,dup2函数重定向标准输出范例

发布时间:2011-06-30 11:36:21 文章来源:www.iduyao.cn 采编人员:星星草
APUE之dup,dup2函数重定向标准输出实例

目的:重定向标准输出到一个文件之中。

定义这两个函数的头文件是 unistd.h 

这个头文件同时定义了下面三个常量:

* STDIN_FILENO = 标准输入

* STDOUT_FILENO = 标准输出

* 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 dup2n"
int main(int argc,char **argv)
{
        int fd;
        fd =open("testdup2",0666);//打开文件操作
        if(fd<0)
        {
        printf("open errorn");
        exit(-1);
        }
        if(dup2(fd,STDOUT_FILENO) < 0) //括号内把输出重定向到fd标识的文件
        {
                printf("error in dup2n");
        }
        printf("TESTSTRn");  
        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 dup2n"
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





友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: