读档,存档
关于读档存档 最方便的是freopen()函数 它的语法是这样的:
FILE *freopen( const char *path, const char *mode, FILE *stream );
比如我们想把输入流切换到 d:\xxx.txt 那么代码就是
freopen("d:\\xxx.txt","r",stdin)//"r"参数后面会说
这个命令的头文件是 <stdio.h>
返回值:成功是path所在路径的指针 失败是NULL
读档
使用如下命令模板:
freopen("d:\\path\\to\\your\\keep.txt","r",stdin);
它后面的所有cin/scanf/getline等都会从这个路径输入
那么我们就可以写出如下函数(用来读档):
char* readkeep(const char*path,\
char(*doit)(char*)=NULL){//第一个是路径 第二个是处理方法
freopen(path,"r",stdin);
char*x;
cin>>x;//应该不用快读吧
char*output;
if(doit)output=doit(x)
else output=x;
fclose(stdin);
return output;
}
非常简单
存档
bool keepit(const char*path,char*put,char(*doit)(char*)=NULL){//put是存档内容(覆盖)其他同上
bool x=freopen(path,"w",stdout);
if(doit)cout<<doit(put);
else cout<<put;
fclose(stdout);
return x;
}
往档里续写内容
bool keepinnext(const char*path,char*put,char(*doit)(char*)=NULL){
return keepit(path,readkeep(path,doit)+put,doit());
}
写成头文件
#include<iostream>
#include<stdio.h>
//不要using namespace std;因为是头文件
//下面两行和最后一行是头文件格式
#ifndef FILENAME_H //把FILENAME替换为你的头文件名字(为了阅读方便 建议大写)
#define FILENAME_H
char*path="D:\\"
char* readkeep(const char*path,char(*doit)(char*)=NULL){
freopen(path,"r",stdin);
char*x;
std::cin>>x;
char*output;
if(doit)output=doit(x)
else output=x;
fclose(stdin);
return output;
}
bool keepit(const char*path,char*put,char(*doit)(char*)=NULL){
bool x=freopen(path,"w",stdout);
if(doit)std::cout<<doit(put);
else std::cout<<put;
fclose(stdout);
return x;
}
bool keepinnext(const char*path,char*put,char(*doit)(char*)=NULL){
return keepit(path,readkeep(path,doit)+put,doit());
}
//补充 新建文件夹
void createfolder(string*path,string*name){
CreateDirectoryA((path+name).c_str(), 0);
}
#endif