利用重定向:
输入重定向:> >> >!
例如 cat ***.txt > log
输入重定向:<
例如 grep hello < log (从log文件中找到hello,作为输入)
对于标准重定向 0-输入;1-输出;2-标准错误
cat 1.c 1>log 2>err
cadasfa 1.c 1>log 2>err
另外:bootargs里的console属性就是用于确定重定向的设备的。
可以在文件开头使用freopen函数,
举例1
| 1 2 3 4 5 6 7 8 9 10 11 12 | #include<stdio.h> int main() { /* redirect standard output to a file */ if(freopen("D:\\output.txt", "w", stdout) == NULL) fprintf(stderr,"error redirecting stdout\n"); /* this output will go to a file */ printf("This will go into a file.\n"); /*close the standard output stream*/ fclose(stdout); return 0; } |
举例2
如果上面的例子您没看懂这个函数的用法的话,请看这个例子。这个例子实现了从stdout到一个文本文件的重定向。即,把输出到屏幕的文本输出到一个文本文件中。
| 1 2 3 4 5 6 7 8 9 10 11 12 | #include<stdio.h> int main() { int i; if (freopen ("D:\\output.txt", "w", stdout) == NULL) fprintf(stderr, "error redirecting stdout\n"); for (i = 0; i < 10; i++) printf("%3d", i); printf("\n"); fclose(stdout); return 0; } |
编译运行一下,你会发现,十个数输出到了D盘根目录下文本文件output.txt中。
举例3
从文件in.txt中读入数据,计算加和输出到out.txt中
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | #include<stdio.h> int main() { int a, b; freopen("in.txt","r",stdin); /* 如果in.txt不在连接后的exe的目录,需要指定路径如D:\in.txt */ freopen("out.txt","w",stdout); /*同上*/ while (scanf("%d%d", &a, &b) != EOF) printf("%d\n",a+b); fclose(stdin); fclose(stdout); return 0; } |