欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

还嫌文件操作太麻烦? XFILE-好用的c++库(更新中~)

程序员文章站 2022-05-23 23:14:07
...

上次更新:1个月前(没什么创意,欢迎投稿)
投稿方式:评论/qq(1745488156)/gihub(xihale)

库地址:传送门
使用方法:

#include <cstdio>
#include "XFILE.h"
int main()
{
	//1.定义的时候声明打开的文件,以a+形式打开
	XFILE file("test.txt");
	//1.2定义并声明打开方式
	XFILE file("test.txt",'w');
	//1.3独立打开文件
	file.open("test.txt");
	//1.3.1独立打开并声明打开方式
	file.open("test.txt","w");
	//1.4写入内容
	file.write("HelloWorld");
	//1.5读取内容
	printf("%s",file.read());
	//1.6改变模式(慎用带w的)
	file.change_mode("a+");
	//1.7复制文件内容到XXX文件
	file.copyTo("test1.txt");
	//1.8从XXX文件复制内容到此文件
	file.copyFrom("test1.txt");
}

头:

#ifndef XFILE_H
#define XFILE_H "xfile_from_xihale"
/*
this class from xihale(https://xihale.top)
*/
class XFILE
{
	public:
		XFILE(){}
		XFILE(const char *filename)
		XFILE(const char *filename,const char *mode)
		bool open(const char *filename)
		bool open(const char *filename,const char *mode)
		bool change_mode(const char *mode)
		bool write(const char *str)
		char *read()
		bool copyTo(const char *filename)
		bool copyFrom(const char *filename)
	private:
		FILE *fp;
		char *filename;
		char *mode;
};
#endif

源码:

#ifndef XFILE_H
#define XFILE_H "xfile_from_xihale"
/*
this class from xihale(https://xihale.top)
*/
class XFILE
{
	public:
		XFILE(){}
		XFILE(const char *filename){this->open(filename);}
		XFILE(const char *filename,const char *mode){this->open(filename,mode);}
		bool open(const char *filename){return open(filename,"a+");}
		bool open(const char *filename,const char *mode)
		{
			this->filename=(char*)filename,this->mode=(char*)mode;
			fp=fopen(filename,mode);
			if(fp)return 1;
			return 0;
		}
		bool change_mode(const char *mode)
		{
			if(!fp||this->mode==mode)return 0;
			fclose(fp);
			fp=fopen(filename,mode);
			if(fp)return 1;
			return 0;
		}
		bool write(const char *str)
		{
			if(!fp)return 0;
			for(int i=0;str[i]!='\0';i++)fputc(str[i],fp);
			return 1;
		}
		char *read()
		{
			this->change_mode("r");
			if(!fp)return 0;
			static char str[10000]={0};
			int i=0;
			while((str[i++]=fgetc(fp))!=EOF);
			this->change_mode("a");
			str[i-1]='\0';
			return str;
		}
		bool copyTo(const char *filename)
		{
			if(!fp)return 0;
			this->change_mode("r");
			FILE *a=fopen(filename,"w");char ch;
			if(!a)return 0;
			while((ch=fgetc(fp))!=EOF)
				fputc(ch,a);
			return 1;
		}
		bool copyFrom(const char *filename)
		{
			this->change_mode("w");
			XFILE a(filename,"r");
			this->write(a.read());
			return 1;
		}
	private:
		FILE *fp;
		char *filename;
		char *mode;
};
#endif