Linux输出重定向到文件(备忘)
通常的命令执行结果的重定向可用:#command [option] > 或 >> filename;
其中,’>’与’>>’的区别为前都会清原来文件中的内容再写入,后者会增加在文件的后面而不清原来的内容。
如果对一个程序中的print等输出进行重定向,则应该在printf后面加下输出的刷新fflush(stdout),不然输出不会马上写入到重定向的文件里,因为重定向后输出只有满4K之后才会写入一次文件中,如下:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char ** argv )
{
while (1)
{
printf( "hello, world!/n" );
fflush(stdout);
sleep(2);
}
return 0;
}
编译程序:gcc –o test test.c
执行重定向:./test > info
如果没有fflush(stdout),则文件info中到等很长很长时间之后才会看到相关的输出信息(等输出信息满4K),而有fflush(stdout)时查看info会马上看到输出信息。
联系客服