【问题标题】:C programming: Redirect the output of an encryption program into a .txt file [closed]C 编程:将加密程序的输出重定向到 .txt 文件 [关闭]
【发布时间】:2017-03-21 12:56:50
【问题描述】:

我已经用 c 编写了一个加密程序,但是如何在 .txt 文件中重定向输出。我没有在这个加密程序中使用文件处理。我尝试过使用重定向运算符(./encrypt>txt.txt)。我正在使用 gcc 编译器。非常感谢您。

【问题讨论】:

  • 在什么情况下使用重定向运算符不起作用?
  • 您需要提供minimal reproducible example。你的程序是否写信给stdout
  • 无来源,无帮助
  • encrypt>txt.txt 这看起来像 cmd 行选项,而不是 std c。使用 fopen 和 fprintf 将其写入文件
  • edit您的问题显示what you have tried so far。您应该至少包含您遇到问题的代码的大纲(但最好是minimal reproducible example),然后我们可以尝试帮助解决具体问题。您还应该阅读How to Ask

标签: shell


【解决方案1】:

假设您正在使用fwrite()printf()(和朋友)将输出写入stdout,您可以使用freopen() 来“重新打开”文件句柄。

以下示例将“重新打开”stdout

#include <stdio.h>
#include <errno.h>

int main(void) {
    FILE *f;

    f = freopen("./output.txt", "w", stdout);
    if (f == NULL) {
        perror("freopen()");
        return 1;
    }

    printf("Hello World!\n");

    return 0;
}

在这里,Hello World! 将被写入./output.txt

如果您注释掉对freopen() 的调用,那么Hello World! 将出现在控制台上。


如果您没有使用fwrite()printf()(而是对“文件描述符”进行操作的较低级别的write() 系列),那么您将需要使用dup2() - 很高兴提供一个示例.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 2017-05-09
    • 1970-01-01
    • 2020-10-24
    • 2021-06-30
    • 1970-01-01
    • 2014-07-01
    相关资源
    最近更新 更多