将输出重定向到C中的文件 [英] redirecting output to a file in C

查看:266
本文介绍了将输出重定向到C中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用C编写了一个用于执行基本命令的基本shell,它将执行命令lsls -alls -al | more等.

i coded a basic shell in C for executing basic commands it'll execute commands ls, ls -al , ls -al | more etc.

我想在我的shell中执行以下命令. 喜欢;

i want to execute following command in my shell. like ;

ls -al > a.txt

这会给我a.txt文件,其中包含ls -al进程的输出. 我找到了一个解决方案,它正在像[command1] | tee [filename]这样的shell中更改命令.在这种情况下,它将ls -al > a.txt更改为ls -al | tee a.txt.但是此过程会将输出也提供给文件和终端.如何停止在终端中打印输出.

this will give me a.txt file which contain output of ls -al process. i found a one solution, it's changing the command in my shell like [command1] | tee [filename]. in this instance it'll change ls -al > a.txt to ls -al | tee a.txt. but this process gives the output to file and terminal as well. how to stop printing output in terminal.

还是有比使用tee命令更好的解决方案. 预先感谢...

or are there are any better solution rather than using tee command. thanks in advance...

推荐答案

这是我用dup2进行测试的结果

This is the result of my testing things out with dup2

更微妙的一点是在正确的时间记住fflush :)否则,您将得到非常令人惊讶的结果.

The more subtle point is remembering fflush at the right times :) Otherwise, you'll get very surprising results.

此外,更喜欢使用fileno而不是对1(stdout)2(stderr)进行硬编码.

Also, prefer fileno instead of hardcoding 1 (stdout) 2 (stderr).

重定向stdin作为练习留给读者

Redirecting stdin was left as an exercise for the reader

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

int main(int argc, const char *argv[])
{
    int out = open("cout.log", O_RDWR|O_CREAT|O_APPEND, 0600);
    if (-1 == out) { perror("opening cout.log"); return 255; }

    int err = open("cerr.log", O_RDWR|O_CREAT|O_APPEND, 0600);
    if (-1 == err) { perror("opening cerr.log"); return 255; }

    int save_out = dup(fileno(stdout));
    int save_err = dup(fileno(stderr));

    if (-1 == dup2(out, fileno(stdout))) { perror("cannot redirect stdout"); return 255; }
    if (-1 == dup2(err, fileno(stderr))) { perror("cannot redirect stderr"); return 255; }

    puts("doing an ls or something now");

    fflush(stdout); close(out);
    fflush(stderr); close(err);

    dup2(save_out, fileno(stdout));
    dup2(save_err, fileno(stderr));

    close(save_out);
    close(save_err);

    puts("back to normal output");

    return 0;
}

这篇关于将输出重定向到C中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆