# 2.1 linux文件系统dup/dup2重定向应用实例

来源:互联网 发布:综合源码集合系 编辑:程序博客网 时间:2024/05/17 19:15

从文件里面读出1000个随机数,进行排序,再写到另一文件中。(考虑使用重定向dup/dup2)

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/stat.h>#include <sys/types.h>#include <fcntl.h>void swp(int *p1, int *p2)  //交换函数{    int tmp;    tmp = *p1;    *p1 = *p2;    *p2 = tmp;}void sort(int *p) //数组排序函数{    int i, j;    for(i = 0; i < 1000; i++) {        for(j = i; j < 1000; j++)            if(p[i] < p[j])                swp(&p[i], &p[j]);    }   }int main(void){    int fd1, fd2;    int array[1000];    int i = 0;    fd1 = open("hello", O_RDONLY);    fd2 = open("result", O_CREAT|O_RDWR, 0644);    dup2(fd1, STDIN_FILENO); //把标准输入重定向到fd1    dup2(fd2, STDOUT_FILENO);//把标准输出重定向到fd2    for(i = 0; i < 1000; i++) {        scanf("%d", &array[i]);//这样就可以用scanf从文件中按回车读取数字到数组中    }    sort(array);//排序    for(i = 0; i < 1000; i++)        printf("%d\n", array[i]);//输出到fd2中去'\n'换行    close(fd1);    close(fd2);    return 0;}

注:dup2(fd1, STDIN_FILENO);是把STDIN_FILENO重定向到fd1
hello中要有1000个随机数,回车间隔

0 0