C++文件操作之freopen

作为一个OIer,文件操作是很重要的。
如果没有文件操作或文件操作被注释,等待着你的就是爆零的命运。
C和C++的文件操作,一般是用fopen或fstream,但在OI里,我们用freopen,即文件重定向。
它的用法其实也挺简单。


包含库:cstdio(stdio.h)
函数原型:

FILE *__cdecl freopen(const char * __restrict__ _Filename,const char * __restrict__ _Mode,FILE * __restrict__ _File) __MINGW_ATTRIB_DEPRECATED_SEC_WARN;

参数:
_Filename:要打开的文件名。
_Mode:打开方式,同fopen。
_File:一个FILE型指针,可以是stdin(标准输入)或stdout(标准输出)。

好像很复杂的样子。其实就是像这样:

freopen("xxx.in","r",stdin);	//输入文件
freopen("xxx.out","w",stdout);	//输出文件

然后其他的代码按原样写就可以了。

接下来是实例代码:

#include
#include
using namespace std;
int main()
{
	freopen("a+b.in","r",stdin);
	freopen("a+b.out","w",stdout);
	//以上是模板
	int a,b;
	cin>>a>>b;
	cout<<a+b<<endl;
	return 0;
}

运行结果:
C++文件操作之freopen_第1张图片
如果你是一个OIer,文件操作模板请烂熟于心。
写代码时可以把文件操作加上注释。
但是,记住:提交代码时一定要把注释打开!


That’s all~

彩蛋:小技巧

#include
#include
using namespace std;
string FILENAME="FILENAME";	//FILENAME 是要求的文件名去掉.in/.out后的部分
							//如要求打开a+b.in/a+b.out FILENAME就是a+b
int main()
{
	freopen((FILENAME+".in").c_str(),"r",stdin);
	freopen((FILENAME+".out").c_str(),"w",stdout);
	//do sth.
	return 0;
}

实例:

#include
#include
using namespace std;
string FILENAME="a+b";
int main()
{
	freopen((FILENAME+".in").c_str(),"r",stdin);
	freopen((FILENAME+".out").c_str(),"w",stdout);
	int a,b;
	cin>>a>>b;
	cout<<a+b<<endl;
	return 0;
}

你可能感兴趣的:(c++)