2011-04-16 145 views
0

我正在C上编写一个Linux程序,我不能使用fprintf打印到文件。我可以使用printf在控制台中进行打印。我如何获取控制台输出并将其写入文件。我试过printf("echo whatever >> file.txt");但我怀疑它不能运行。从控制台打印到文件

感谢

+0

'系统( “回声无论>> file.txt的”);'应该工作,但如果你不能用'fprintf',为什么你可以使用'system' ^^。 – Simon 2011-04-16 17:47:59

回答

2

运行程序时,追加> file.txt它应该工作。

./program > file.txt

IIRC,重新路由STDOUT的文件。

+0

这看起来像我正在寻找的解决方案。它创建文件,但似乎没有写入它。我正在运行的程序有一个参数,所以我应该在arg之前还是之后使用它?我曾尝试过,但无济于事...... – Ferguzz 2011-04-16 17:59:09

+0

你想要做什么打印? – TyrantWave 2011-04-16 18:01:19

0

编译并运行您的程序一样,

./program > lala.txt 

这将 “推” 所有的printf()年代到lala.txt

0

可以freopenstdout流。

#include <stdio.h> 

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

您试图让程序输出一些文本,并将shell作为命令评估输出。

这是不寻常的,一个通常分离生成所述文本到程序的责任,然后让壳重定向输出到一个文件:

的foo.c包含:

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

然后运行您的程序和标准输出重定向到你喜欢的地方:

$a.out >> file.txt 
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; 
}