c++ 常用函数

#include <iostream>  
#include <io.h>
#include <direct.h>
#include <time.h>
#include <string>
#include <vector>

using namespace std;

//读取某给定路径下所有文件夹与文件名称,并带完整路径
void getAllFilesInDirs(string path, vector<string>& fileFullpath) {

	_finddata_t fileInfo;
	string s;
	const char* filePath = s.assign(path).append("\\*.*").c_str();
	//将string转化为const char*类型 
	intptr_t fileHandle = _findfirst(filePath, &fileInfo);
	//读取第一个文件信息 文件句柄类型为long会出现不兼容[Win10平台用long声明文件句柄会crash] 
	string f;
	if (fileHandle == -1) {
		cout << "error\n";
		return;
	}
	while (_findnext(fileHandle, &fileInfo) == 0) {

		if (fileInfo.attrib & _A_SUBDIR) {
			if (strcmp(fileInfo.name, ".") == 0 || strcmp(fileInfo.name, "..") == 0)  continue;
			string newPath = path + "\\" + fileInfo.name;
			getAllFilesInDirs(newPath, fileFullpath);
		}
		else {
			f = path + string("\\") + string(fileInfo.name);
			fileFullpath.push_back(f);
		}
	};
	_findclose(fileHandle);
}


////读取某给定路径下后缀名为format得文件名称,并带完整路径
void getAllFilesByformat(string path, vector<string>& fileFullpath, string format) {
	_finddata_t fileInfo;
	string s;
	const char* filePath = s.assign(path).append("\\*").append(format).c_str();
	//将string转化为const char*类型 
	intptr_t fileHandle = _findfirst(filePath, &fileInfo);
	//读取第一个文件信息 文件句柄类型为long会出现不兼容[Win10平台用long声明文件句柄会crash] 
	string f;
	if (fileHandle == -1) {
		cout << "error\n";
		return;
	}
	while (_findnext(fileHandle, &fileInfo) == 0) {

		if (fileInfo.attrib & _A_SUBDIR) {
		}
		else {
			f = path + string("\\") + string(fileInfo.name);
			fileFullpath.push_back(f);
		}
	};
	_findclose(fileHandle);
}

// 获取文件后缀名
string getExtension(string filename) {
	return filename.substr(filename.find_last_of('.') + 1);
}

// 字符串分割到 vector
vector<string> string_split(const string& str, const string& delim) {
	vector<string> res;
	if ("" == str) return res;
	//先将要切割的字符串从string类型转换为char*类型  
	char * strs = new char[str.length() + 1]; //不要忘了  
	strcpy(strs, str.c_str());

	char * d = new char[delim.length() + 1];
	strcpy(d, delim.c_str());

	char *p = strtok(strs, d);
	while (p) {
		string s = p; //分割得到的字符串转换为string类型  
		res.push_back(s); //存入结果数组  
		p = strtok(NULL, d);
	}

	return res;
}


// 递归创建文件夹
int self_mkdirs(string filename) {
	filename += "\\";
	char *fileName = (char*)filename.c_str();
	char *tag;
	int a = 0;
	for (tag = fileName; *tag; tag++, a++)
	{
		if (*tag == '\\')
		{
			string new_path = filename.substr(0, a + 1);

			if (_access(new_path.c_str(), 0) == -1)	//如果文件夹不存在
				_mkdir(new_path.c_str());				//则创建
		}
	}

	return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/dxscode/p/11698344.html