我如何实现input.txt> C中的output.txt

时间:2016-09-15 02:19:47

标签: c io stream

如何在C中实现单个I / O流? 即a> b
下面的代码不会像我想要的那样将文本从input.txt传输到output.txt。

#include <fcntl.h>   
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>   
#include <unistd.h>   

int main(void)
{
        int fd = open("/home/ubuntu/workspace/file2.txt", O_WRONLY|O_CREAT);
        if (fd < 0)
        {
            fprintf(stderr, "Failed to open file2.txt for writing\n");
            return(EXIT_FAILURE);
        }
        dup2(fd, 1);
        close(fd);
        execlp("a.out", "a.out", "file1.txt", NULL);
}

1 个答案:

答案 0 :(得分:2)

如果你没有被迫使用exec,你可以使用简单的代码将file1.txt写入指定的输出文件:

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define BUFFSIZE 10240

int main(int argc, char *argv[]) {
    int n, t, i;
    char buf[BUFFSIZE];
    t = open("file1.txt", O_RDONLY);

    while ((n = read(t, buf, BUFFSIZE)) > 0) {
        if (write(STDOUT_FILENO, buf, n) != n) {
            perror("Write Error");
        }
    }
    if (n < 0) {
        perror("Read Error");
    }
    if (close(t) == -1) {
        perror("Closing Error");
    }

    exit(0);
}

测试

./a.out a > c

dac@dac-Latitude-E7450 ~/C/twodec> more c
foo bar
bletch 
blahonga