c++文件各种操作

这里写自定义目录标题

c++文件各种操作

自己参考写的封装代码,可以参考一下。
环境是是VS2015,release x64,多字节编码。

头文件

#pragma once
#ifndef _FILEOPERATION_H_
#define _FILEOPERATION_H_
#define _CRT_SECURE_NO_WARNINGS

#include <string>
#include<iostream>
#include <direct.h>
#include <windows.h>
#include <time.h>
#include <vector>
#include <tchar.h>
#include <stdlib.h>
#include <shellapi.h>

using namespace std;


class FileOperation
{

public:
	string m_strPath;
	vector<string> m_fileList;
	vector<int> m_lableList;
	vector<string> m_noLableFileList;

public:
	FileOperation(/*string dir*/);
	~FileOperation(void);


	//创建文件
	int CreatFile(string filename);
	//删除文件
	int DeleteFile(string filename);
	//更改filename文件名字为newname
	int AlterFileName(string filename,string newname);
	//判断目录是否存在;
	int IsExisteDirectory(string path);
	//计时器
	double getDoubleTimeSecond();
	//日志
	static void userlog(char* info);
	// 获取文件列表到当前目录的txt,以追加的方式写入文件,lable是标志符,标志位不为255,255代表空。
	void GetFileList(string filePath, char* distAll, string format, int lable);
	//读取文件列表文件与标志位
	void ReadFileList(string filename);
	//读取标志位
	int getClassFlag(string strPath);
	//读取不含标志位的文件列表文件
	void readNoLableFileList(string filename);
	//选择文件,并记录文件名
	//使用说明,一句话的事情,就是getopenfilename这个函数是mfc函数的,
	//如果你的文件头中有#define WIN32_LEAN_AND_MEAN那么你的系统会提示,
	//getopenfilename未定义,顺带的OPENFILENAME的结构也会变成未定义的、
	string  SelectFile();
	//创建指定路径文件夹,返回1,创建成功,返回0创建失败。
	int MakeFile(const string *OUTPUT_FILENAME);
	//查询指定文件夹是否为空,不是空返回1,是空的或者不存在返回0.
	int FolderIsnotEmpty(const string *OUTPUT_FILENAME);
	//弹出文件夹
	void PopUpFolder(string filename);


public:
	//辅助函数
	//获取所有的文件名
	void GetAllFiles(string path, vector<string>& files);
	//获取特定格式的文件名(单一文件目录下,不查找子目录)
	void GetAllFormatFiles(string path, vector<string>& files, string format);
	//获取特定格式的文件名(可遍历寻找子目录)
	void GetFormatFiles(string path, vector<string>& files, string fotmat);

};
#endif // !_FILEOPERATION_H_
/*
参考博客 
https://blog.csdn.net/CosmopolitanMe/article/details/80629531
https://blog.csdn.net/sinat_25923849/article/details/78268984

*/

源码

#include "fileoperation.h"


#include <fstream>
#include <io.h>
//#define _CRT_SECURE_NO_WARNINGS

FileOperation::FileOperation(/*string dir*/) {

	// 给m_strPath赋初值
	//string path = _pgmptr;  // exe文件所在目录,带*.exe
	//m_strPath = path.substr(0, path.find_last_of('\\') + 1);
	//m_strPath += dir;

	//if (!IsExisteDirectory(m_strPath))
	//{
	//	string str = "md \"" + m_strPath + "\"";
	//	system(str.c_str());
	//}
	m_fileList.clear();
	m_lableList.clear();
	m_noLableFileList.clear();

}
FileOperation::~FileOperation(void) {
	m_fileList.clear();
	m_lableList.clear();
	m_noLableFileList.clear();

}

//创建文件
int FileOperation::CreatFile(string filename) {

	if ((_access(filename.c_str(), 0)) == -1)
	{
		//not exist
		fstream file;
		file.open(filename, ios::out);
		if (!file)
		{
			//cout << "创建失败"<< endl;
			return -1;
		}
		file.close();
		return 0;
	}
}
//删除文件
int FileOperation::DeleteFile(string filename) {

	
	// int remove(char *filename);
	// 删除文件,成功返回0,否则返回-1
	if ((_access(filename.c_str(), 0)) == 0)
	{
		//exist
		//删除文件
		if (-1 == remove(filename.c_str()))
		{
			return -1;
		}

		return 0;
	}
}

//更改filename文件名字为newname
int FileOperation::AlterFileName(string filename, string newname) {

	//string path = m_strPath + '\\' + filename;
	//newname = m_strPath + '\\' + newname;
	// int rename(char *oldname, char *newname);
	// 更改文件名,成功返回0,否则返回-1
	if (-1 == rename(filename.c_str(), newname.c_str()))
	{
		return -1;
	}

	return 0;
}

//判断目录是否存在;
int FileOperation::IsExisteDirectory(string path) {

	if (-1 != _access(path.c_str(), 0))
	{
		return 0;
	}
	return -1;

}
//计时器
double FileOperation::getDoubleTimeSecond() {

	LARGE_INTEGER t, freq;
	QueryPerformanceCounter(&t);
	QueryPerformanceFrequency(&freq);
	return t.QuadPart*1.0 / freq.QuadPart;


}
//日志
//使用
//char info[1024];
//sprintf(info, "图像未处理,跳过");
//userlog(info);

void FileOperation::userlog(char* info) {
	time_t t;
	time(&t);
	char szTime[100];

	struct tm tm1 = *localtime(&t);
	sprintf(szTime, "[%4.4d-%2.2d-%2.2d %2.2d:%2.2d] ",
		tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday,
		tm1.tm_hour, tm1.tm_min);


	FILE * fp = fopen("d:\\Log\\log.txt", "a");
	if (fp) {
		fwrite(szTime, 1, strlen(szTime), fp);
		fwrite(info, 1, strlen(info), fp);
		fwrite("\n", 1, 1, fp);
		fclose(fp);
	}
}

// 获取文件列表到当前目录的filelist.txt,以追加的方式写入文件
//第一个参数是文件路径
//第二个参数是文件名
//第三个参数是文件格式
//第四个参数是文件标签
//标签不为255
//标签与文件路径之间有一个空格
void FileOperation::GetFileList(string filePath, char* distAll, string format, int lable) {

	vector<string> files;
	//char * distAll = "filelist.txt";
	GetAllFormatFiles(filePath, files, format);
	ofstream ofn(distAll, ios::app);
	int size = files.size();
	//ofn << size << endl;
	if (lable != 255)
	{
		for (int i = 0; i < size; i++)
		{
			ofn << files[i] << " " << lable << endl;
			//cout << files[i] << endl;
		}
	}
	else
	{
		for (int i = 0; i < size; i++)
		{
			ofn << files[i] << endl;
			//cout << files[i] << endl;
		}
	}
	ofn.close();


}

//获取所有的文件名
void FileOperation::GetAllFiles(string path, vector<string>& files) {

	long long  hFile = 0;
	//文件信息  
	struct _finddata_t fileinfo;
	string p;
	if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
	{
		do
		{
			if ((fileinfo.attrib &  _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
				{
					files.push_back(p.assign(path).append("\\").append(fileinfo.name));
					GetAllFiles(p.assign(path).append("\\").append(fileinfo.name), files);
				}
			}
			else
			{
				files.push_back(p.assign(path).append("\\").append(fileinfo.name));
			}

		} while (_findnext(hFile, &fileinfo) == 0);

		_findclose(hFile);
	}

}

//获取特定格式的文件名
void FileOperation::GetAllFormatFiles(string path, vector<string>& files, string format) {

	//文件句柄  
	long long   hFile = 0;
	//文件信息  
	struct _finddata_t fileinfo;
	string p;
	if ((hFile = _findfirst(p.assign(path).append("\\*" + format).c_str(), &fileinfo)) != -1)
	{
		do
		{
			if ((fileinfo.attrib &  _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
				{
					//files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
					GetAllFormatFiles(p.assign(path).append("\\").append(fileinfo.name), files, format);
				}
			}
			else
			{
				files.push_back(p.assign(path).append("\\").append(fileinfo.name));
			}
		} while (_findnext(hFile, &fileinfo) == 0);

		_findclose(hFile);
	}


}
//读取文件列表文件与标志位
void FileOperation::ReadFileList(string filename) {

	m_fileList.clear();
	m_lableList.clear();
	ifstream readData(filename, ios::in);
	string buffer;
	int nClass = 0;
	while (readData)
	{
		if (getline(readData, buffer))
		{

			if (buffer.size() > 0)
			{
				//标签与文件路径之间有一个空格
				nClass = getClassFlag(buffer);
				m_lableList.push_back(nClass);
				string temp(buffer, 0, buffer.size() - 2);
				m_fileList.push_back(temp);//图像路径  
			}
		}
	}
	readData.close();

}

//读取标志位
int FileOperation::getClassFlag(string strPath) {

	int len = strPath.size();
	char drt = strPath[len - 1];
	int temp = drt - '0';
	return temp;
}
//读取不含标志位的文件列表文件
void FileOperation::readNoLableFileList(string filename) {

	ifstream readData(filename);  //加载测试图片集合
	string buffer;
	while (readData)
	{
		if (getline(readData, buffer))
		{
			m_noLableFileList.push_back(buffer);//图像路径       
		}
	}
	readData.close();

}

//选择文件,并记录文件名
string  FileOperation::SelectFile() {
#ifdef  _UNICODE
	TCHAR szBuffer[MAX_PATH] = { 0 };
	OPENFILENAME ofn = { 0 };
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = NULL;
	ofn.lpstrFilter = _T("All(*.*)\0*.*\0Text(*.txt)\0*.TXT\0\0");//要选择的文件后缀 
																  //ofn.lpstrInitialDir = _T("D:\\Program Files");//默认的文件路径 
	ofn.lpstrFile = szBuffer;//存放文件的缓冲区 
	ofn.nMaxFile = sizeof(szBuffer) / sizeof(*szBuffer);
	ofn.nFilterIndex = 0;
	ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER;//标志如果是多选要加上OFN_ALLOWMULTISELECT
																	 //BOOL bSel = GetOpenFileName(&ofn);
	if (GetOpenFileName(&ofn))
	{
		//wprintf(L"%s\n", ofn.lpstrFile);  //ofn.lpstrFile  是地址
		/*locale loc("chs");   //输出到控制台
		wcout.imbue(loc);
		wcout << ofn.lpstrFile << endl;
		*/
		char szcConv[200];
		memset(szcConv, 0, 200 * sizeof(char));

		size_t wLen = wcslen(ofn.lpstrFile) + 1;  // 宽字符字符长度,+1表示包含字符串结束符
		int aLen = WideCharToMultiByte(CP_ACP, 0, ofn.lpstrFile, wLen, NULL, 0, NULL, NULL);

		LPSTR lpa = new char[aLen];
		WideCharToMultiByte(CP_ACP, 0, ofn.lpstrFile, wLen, lpa, aLen, NULL, NULL);
		strcpy_s(szcConv, 200, lpa);
		delete[] lpa;
		lpa = NULL;
		//wcout << szcConv << endl;
		string FileName;
		FileName = szcConv;
		return szcConv;
	}

#endif
#ifdef  _MBCS

	char szFileName[MAX_PATH] = { 0 };
	OPENFILENAME openFileName = { 0 };
	openFileName.lStructSize = sizeof(OPENFILENAME);
	openFileName.nMaxFile = MAX_PATH;  //这个必须设置,不设置的话不会出现打开文件对话框
	openFileName.lpstrFilter = "All(*.*)\0*.*\0Text(*.txt)\0*.TXT\0\0";
	//默认的文件路径 
	openFileName.lpstrInitialDir = "F:\\demo\\地铁燃弧\\测试数据\\GatherPath";
	openFileName.lpstrFile = szFileName;
	openFileName.nFilterIndex = 1;
	openFileName.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
	string FileName;
	if (::GetOpenFileName(&openFileName))
	{
		//::MessageBoxA(NULL, openFileName.lpstrFile, "", MB_OK);
		//cout << szFileName << endl;

		FileName = szFileName;
		//cout << FileName << endl;
		return FileName;
	}
#endif

}
//创建指定路径文件夹,返回1,创建成功,返回0创建失败。
int FileOperation::MakeFile(const string *OUTPUT_FILENAME) {
	/第一种方法,返回值为1 ,不存在文件夹,需要创建。
	if (_access(OUTPUT_FILENAME->c_str(), 0) == -1)
	{
		//调试语句
		//cout << OUTPUT_FILENAME << endl << " is not existing" << endl;  

		//生成文件夹
		string command;
		command = "mkdir " + *OUTPUT_FILENAME;    //注意星号 
		system(command.c_str());

		//调试语句
		//cout << "***********************************************" << endl;
		//cout << OUTPUT_FILENAME << endl << " make successfully" << endl;

		return  1;
	}
	else
	{
		//
		//cout << OUTPUT_FILENAME << endl << " exists" << endl;
		// cout << "文件存在,不需要创建" << endl;
		return  0;

	}

	//第一种方法的另一种写法(推荐上方写法)

	/*string dir = "./test";
	if (_access(dir.c_str(), 0) == -1)
	{
	cout << dir << " is not existing" << endl;
	int flag = _mkdir(dir.c_str());

	if (flag == 0)
	{
	cout << "make successfully" << endl;
	}
	else {
	cout << "make fsiled" << endl;
	}
	}

	if (_access(dir.c_str(), 0) == 0)
	{
	cout << dir << " exists" << endl;
	cout << "now delete it" << endl;
	int flag = _rmdir(dir.c_str());
	if (flag == 0)
	{
	cout << "delete it successfully" << endl;
	}
	else {
	cout << "delete it errorly" << endl;
	}
	}*/


	//第二种方法
	//使用system命令, mkdir -p  会在当前目录下生成名为 -p 文件夹,在输出目录也生成文件夹
	/使用mkdir,只会在输出目录生成文件夹
	//command = "mkdir -p" + OUTPUT_FILENAME;
	//system(command.c_str());


	第三种方法
	//C++风格
	/会在当前目录下生成txt文件
	/* ofstream out("./my.txt");
	if (out.is_open())
	{
	out << "This is a line.\n";
	out << "This is another line.\n";
	out.close();
	}*/

	//c风格
	/*FILE *fp=fopen((OUTPUT_FILENAME+"\\my.txt").c_str(),"w");
	fprintf(fp,"卧了个槽 ");
	fprintf(fp, "%d",885);
	fclose(fp);*/


	//system("pause");
	//return 0;


}

//查询指定文件夹是否为空,不是空返回1,是空的或者不存在返回0.
int FileOperation::FolderIsnotEmpty(const string *OUTPUT_FILENAME) {

	HANDLE hFind;
	WIN32_FIND_DATA FindFileData;
	string testfilename = *OUTPUT_FILENAME + "\\*.*";
	if ((hFind = FindFirstFileA(testfilename.c_str(), &FindFileData)) != INVALID_HANDLE_VALUE)
	{
		BOOL bFind = TRUE;
		BOOL EmptyDirectory = TRUE;
		while (bFind)
		{
			if (strcmp(FindFileData.cFileName, ".") == 0
				|| strcmp(FindFileData.cFileName, "..") == 0)
			{
				bFind = FindNextFile(hFind, &FindFileData);
			}
			else
			{
				//有子文件夹也算非空
				EmptyDirectory = FALSE;
				break;
			}
		}
		if (EmptyDirectory)
		{
			//cout << "Folder Is Empty" << endl;
			return 0;
		}
		else
		{
			//cout << "Folder Is Not Empty" << endl;
			return 1;
		}
	}
	else
	{
		//cout << "Path does not exist." << endl;
		return 0;
	}
}

//弹出文件夹
void FileOperation::PopUpFolder(string filename) {

	ShellExecute(NULL, "explore", filename.c_str(), NULL, NULL, SW_SHOWNORMAL);

}
void FileOperation::GetFormatFiles(string path, vector<string>& files, string fotmat)
{
	//文件句柄    
	long long   hFile = 0;
	//文件信息    
	struct _finddata_t fileinfo;
	string p;
	int fotmatlength = fotmat.length();

	if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
	{

		do
		{
			if ((fileinfo.attrib &  _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
				{
					GetFormatFiles(p.assign(path).append("\\").append(fileinfo.name), files, fotmat);
				}
			}
			else
			{
				string strtemp = fileinfo.name;
				int maxchar = strtemp.length();
				if (maxchar > fotmatlength)
				{
					string rightstr = strtemp.substr(maxchar - fotmatlength, fotmatlength);
					if (rightstr == fotmat)
					{
						files.push_back(p.assign(path).append("\\").append(fileinfo.name));
					}
				}
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}

}

测试代码

#include "fileoperation.h"
#include <string>
#include <io.h>
#include <stdio.h>

using namespace std;
int main(int argc,char** argv)
{

	FileOperation a;

	vector<string> file;

	//a.GetAllFormatFiles("F:\\黑马最新c、c++全栈培训第24期高清(全)", file,".txt");
	//a.GetAllFiles("F:\\黑马最新c、c++全栈培训第24期高清(全)", file);
	
	a.GetFormatFiles("F:\\黑马最新c、c++全栈培训第24期高清(全)", file, ".txt");
	
	//int filecouts = file.size();
	
	system("pause");
	return 0;

}


欢迎补充,使用,有问题后面再改。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值