如何在写入文件和打印之间切换 C

How to Switch between writing to file and printing in C

描述

我正在尝试用 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 SSEECCTTIIOONNSS)

这样的输出

how can switch between two

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

在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

last problem is my foo.txt is wrong there are outputs like (MMAANNUUAALL SSEECCTTIIOONNSS)

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

I am pretty new to both c

编译所有可能的警告-Wall -Wextra。使用 sanitizer -fsanitize=addressvalgrind 检查您的程序是否正确。