从控制台打印到文件

时间:2011-04-16 17:44:52

标签: c linux console printf

我正在用C语言在Linux上编写程序,我无法使用fprintf打印到文件。我可以使用printf在控制台中打印。如何获取控制台输出并将其写入文件。

我试过printf("echo whatever >> file.txt");,但我怀疑它没有运行。

由于

5 个答案:

答案 0 :(得分:2)

运行程序时,将> file.txt附加到它应该可以正常工作。

./program > file.txt

IIRC,将STDOUT重新路由到文件。

答案 1 :(得分:1)

您正在尝试让程序输出一些文本,并且shell会将输出评估为命令。

这是不寻常的,通常会将生成文本的职责分离到程序,然后让shell将该输出重定向到文件:

foo.c包含:

...
printf("whatever");
...

然后运行程序并将标准输出重定向到您喜欢的位置:

$a.out >> file.txt

答案 2 :(得分:0)

编译并运行你的程序

./program > lala.txt

这会将您printf()的所有内容“推送”到lala.txt

答案 3 :(得分:0)

您可以freopen stdout信息流。

#include <stdio.h>

int main(void) {
  if (freopen("5688371.txt", "a", stdout) == NULL) {
    /* error */
  }
  printf("Hello, world!\n");
  return 0;
}

答案 4 :(得分:0)

您可以freopendup2如下:

#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
    int f = open("test.txt", O_CREAT|O_RDWR, 0666);
    dup2(f, 1);
    printf("Hello world\n");
    printf("test\n");
    close(f);
    return 0;
}
相关问题