【问题标题】:How to Switch between writing to file and printing in C如何在 C 中写入文件和打印之间切换
【发布时间】:2021-03-23 08:59:51
【问题描述】:

说明

我正在尝试用 C 语言制作一个可以在终端中运行的基本应用程序。 我的目标是编写一个代码,用 dup2(foo, STDOUT_FILENO); 在文件中打印一些输出。 一些输出到终端。问题是我无法理解如何在其中两个之间切换。 我读了几个问题,但我无法理解。

错误/问题

当我用 C 编写时

  int foo = open("./foo.txt", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
  dup2(foo, STDOUT_FILENO);
  sytem("man man"); //trying yo write man in foo.txt
  some_macig_function();
  printf("welcome back to terminal output");

我不知道什么是 macig_fonciton,即使我的子进程已完成,我的代码也会继续写入文件(我猜),第二个也是最后一个问题是我的 foo.txt 错误,输出如下( MMAANNUUAALL SSEECCTTIIONNSS)

【问题讨论】:

  • 您确实需要在代码中进行错误检查。例如,永远不要假设对open 的调用会成功。
  • 我是 linux 和 c 的新手,我怎么能做到这一点
  • @KamilCuk 我在 foo.txt 中打印 man man 输出而不是控制台,但在那之后,我的代码确实写入了文件和 shell。我的 txt 变成 man man outs 并带有一些重复的字符,欢迎回到终端输出。我在终端 agin 看到欢迎回到终端
  • @KamilCuk man 似乎能够检测它是否在 tty 或管道中运行,请尝试 man man | cat -。我猜 OP 正在打那个案子
  • @alagner man -P cat man 也应该可以工作。

标签: c linux system


【解决方案1】:

如何在两个之间切换

使用临时文件描述符来存储标准输出。

在 bash 中你可以练习它:

exec {tempfd}<&1       # copy stdout to temporary fd
exec 1>./foo.txt       # redirect to file
man man
exec 1>&${tempfd}      # restore stdout
echo welcome back to terminal output

在 C 中类似:

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

int main(void) {
    int tempfd = dup(STDOUT_FILENO);      // exec {tempfd}<&1
    int filefd = open("./foo.txt", O_WRONLY | O_CREAT | O_TRUNC);
    dup2(filefd, STDOUT_FILENO);             // exec 1>./foo.txt
    system("echo man man");
    dup2(tempfd, STDOUT_FILENO);          // exec 1>&${tempfd}
    printf("welcome back to terminal output\n");

    system("echo ---- THIS IS IN foo.txt file: ---");
    system("cat foo.txt");

    return 0;
}

outputs on repl:

welcome back to terminal output
---- THIS IS IN foo.txt file: ---
man man

最后一个问题是我的 foo.txt 错误,有类似 (MMAANNUUAALL SSEECCTTIIONNSS) 的输出

Redirecting man page output to file results in double letters in words

我对这两个c都很陌生

编译所有可能的警告-Wall -Wextra。使用消毒剂-fsanitize=address 和valgrind 检查您的程序是否正确。

【讨论】:

  • 非常感谢,但我仍然打印文件和终端@KamilCuk
  • I still prints file and terminal 好吧,我不明白。请尽量具体。在哪里打印什么?输出是否同时打印到文件和终端? man man 输出是否同时打印到文件和终端? welcome back 消息是否同时打印到文件和终端?如果是这样 - 您的问题错过了 minimal reproducible example - 如果是这样,请发布完整的 minimal 程序,其中包含所有相关的 #include 和 main 需要具有相同的行为。
  • İt 仍然打印“欢迎回到终端输出”到文件和终端其他部分是正确的与您的响应的唯一区别是我使用 print 而不是 puts deu 来检查孩子的 id 这就是@KamilCuk
  • 当然,有一个错字。 dup2 args 顺序错误!
  • 非常感谢,它完美运行,只有异常是当我写 man KamillCuk 打印很棒 :)
猜你喜欢
  • 2016-06-15
  • 2011-11-05
  • 2010-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
相关资源
最近更新 更多