<>重定向
如果使用标准的printf输出,有一个比较简便的方法,可以将程序的结果写入一个文件。使用<和>符号,将程序运行结果重定向到文件中去,具体使用到的代码如下:
./test > 12.out //将运行结果写入文件12.out
more 12.out //查看
cat > 12.in //将终端内容输入12.in
./test < 12.in //运行test,输入为文件12.in
./test < 12.in > 12.out //输入为文件12.in,输出为文件12.out
FILE
定义FILE类型变量,使用fopen函数打开该文件,fscanf和fprintf作为文件的读和写,最后使用fclose关闭文件。打开文件的标准代码如下:
FILE * fp=fopen("file",“r”); //FILE是个结构,但是不需要了解到底有什么东西,只要知道用什么方式去用即可。file是文件名,r是读
if(fp){ //fp是fopen的返回值,如果能打开返回true,否则返回错误。
fscanf(fp,...);
fclose(fp);
}else{
...
}
举例如下:
#include <stdio.h>
int main(int argc,char const *argv[]){
FILE *fp=fopen("12.in","r");
if(fp){
int num;
fscanf(fp,"%d",&num);
printf("%d
",num);
fclose(fp);
}else{
printf("无法打开文件
");
}
return 0;
}
fopen函数有两个参数,第一个是文件名,是个字符串,第二个参数也是字符串,比如r是读,有以下几个选项: