常用函数

utils.h 

#ifndef _UTILS_H_
#define _UTILS_H_
#include <string>
#include <list>
#include <vector>
#include <windows.h>
//导出函数
#ifdef UTILS_EXPORTS
#define UTILS_API	__declspec(dllexport)
#else 
#define UTILS_API	__declspec(dllimport)
#endif

namespace UTILS
{
	class UTILS_API CUtils
	{
	public:
		static int add(int a, int b);//例子程序
		static std::wstring Ansi_To_Unicode(const std::string& str);
		static std::string Unicode_To_Ansi(const std::wstring& wstr);
		static std::wstring Utf8_To_Unicode(const std::string& str);
		static std::string Unicode_To_Utf8(const std::wstring& wstr);
		static std::string Utf8_To_Ansi(const std::string& str);
		static std::string Ansi_To_Utf8(const std::string& str);

		//文件路径,操作
		static std::wstring getAppFullpath();//获取当前进程全路径
		static std::wstring getFileExtension(const std::wstring & strPath);//获取文件的扩展名
		static std::wstring removeExtension(const std::wstring & strPath);//去除文件的扩展名
		static std::wstring getFileName(const std::wstring & strPath);//获取文件名,不包含扩展名
		static std::wstring getFileFolder(const std::wstring & strPath);//获取文件所在的文件夹路径
		static int getFileSize(std::string& filePath);//获取文件大小,字节单位
		static void copyFile(const char* src, const char* dst);//复制文件
		static int createDirectory(const wchar_t* dir);//创建目录,如果存在,则不会覆盖原来的文件
		static bool isFileExist(const wchar_t* strPath);//判断文件,目录是否存在
		static bool isFileExistA(const char* strPath);//判断文件,目录是否存在
		static void getFiles(std::string path, std::list<std::string>& files);//获取指定路径下的所有文件
		static bool deleteFiles(std::string path);//删除指定目录下的所有文件,不删除该目录
		static bool deleteFilesEx(std::string path);//删除指定目录下的所有文件,并且删除该目录
		static bool moveFile(std::string srcPath, std::string dstPath);//移动指定文件到指定路径

		//格式化字符串
		static std::string & string_format(std::string & _str, const char * _Format, ...);//格式化string
		static std::wstring & wstring_format(std::wstring & _str, const wchar_t * _Format, ...);//格式化wstring

		static bool isANum(std::wstring strNum);//判断一个字符串是否为数字,十进制
		static bool isANum(std::string strNum);//判断一个字符串是否为数字,十进制
		static bool deleteOldFiles(std::string path,int seconds);//遍历path文件夹,删除指定seconds之前修改的以fileExtension结尾的文件
		static void SplitString(const std::string& s,std::vector<std::string>& v,const std::string& c);//分割字符串
		static void SplitWString(const std::wstring& s,std::vector<std::wstring>& v,const std::wstring& c);//分割字符串
		static bool IsTimeString(std::wstring strTime);//判断字符串是否为时间格式,例如 01:28:39
		static std::wstring& UpperString(std::wstring& s);//将字符串转成大写
		static std::wstring& LowerString(std::wstring& s);//将字符串转成小写
		static std::wstring ToWindowSeprator(std::wstring& s);// 
	};

	class UTILS_API CBase64
	{
	public:
		static std::string base64_encode(unsigned const char*, unsigned int len);
		static std::string base64_decode(const std::string&s);
	};

	class UTILS_API CLog
	{
	public:
		//在指定文件路径写入指定信息,unicode版本
		void WriteLog(const wchar_t* filePath, const wchar_t* text);
		//在指定文件路径写入指定信息,ANSI版本
		void WriteLog(const char* filePath, const char* text);
		//在指定文件路径写入指定信息,格式化字符串版本
		void WriteLogEx(const char* filePath, const char* const format, ...);
	};
	

	extern "C" UTILS_API int sub(int a, int b);//例子程序
}

#endif // !_UTILS_H_

utils.cpp

#include "utils.h"
#include <codecvt>
#include <windows.h>
#include <fstream>
#include <shlobj.h>
#include <memory>
#include <stdlib.h>
#include <io.h>
#include <algorithm>

namespace UTILS
{
	int CUtils::add(int a, int b)
	{
		return a + b;
	}
	int sub(int a, int b)
	{
		return a - b;
	}

	std::wstring CUtils::Ansi_To_Unicode(const std::string& str)
	{
		int unilen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
		wchar_t* pWch = new wchar_t[unilen + 1];
		memset(pWch, 0, sizeof(wchar_t)*(unilen + 1));
		::MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), pWch, unilen);
		std::wstring rt;
		rt = (wchar_t*)pWch;
		delete[]pWch;
		return rt;
	}

	std::string CUtils::Unicode_To_Ansi(const std::wstring& wstr)
	{
		int newlen = ::WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
		char* pCh = new char[newlen + 1];
		memset(pCh, 0, (newlen + 1) * sizeof(char));
		::WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.length(), pCh, newlen, NULL, NULL);
		std::string str = pCh;
		delete[]pCh;
		return str;
	}

	std::wstring CUtils::Utf8_To_Unicode(const std::string& str)
	{
		int newlen = ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
		wchar_t* wCh = new wchar_t[newlen + 1];
		memset(wCh, 0, (newlen + 1) * sizeof(wchar_t));
		::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), wCh, newlen);
		std::wstring wstr = wCh;
		delete[]wCh;
		return wstr;
	}

	std::string CUtils::Unicode_To_Utf8(const std::wstring& wstr)
	{
		int newlen = ::WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
		char* ch = new char[newlen + 1];
		memset(ch, 0, (newlen + 1) * sizeof(char));
		::WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.length(), ch, newlen, NULL, NULL);
		std::string str = ch;
		delete[]ch;
		return str;
	}

	std::string CUtils::Utf8_To_Ansi(const std::string& str)
	{
		int newlen1 = ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
		wchar_t* pWch = new wchar_t[newlen1 + 1];
		memset(pWch, 0, (newlen1 + 1) * sizeof(wchar_t));
		::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pWch, newlen1);
		int newlen2 = ::WideCharToMultiByte(CP_ACP, 0, pWch, -1, NULL, 0, NULL, NULL);
		char* pch = new char[newlen2 + 1];
		memset(pch, 0, (newlen2 + 1) * sizeof(char));
		::WideCharToMultiByte(CP_ACP, 0, pWch, newlen1, pch, newlen2, NULL, NULL);
		std::string strrt = pch;
		delete[]pch;
		delete[]pWch;
		return strrt;
	}

	std::string CUtils::Ansi_To_Utf8(const std::string& str)
	{
		int newlen1 = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
		wchar_t* pWch = new wchar_t[newlen1 + 1];
		memset(pWch, 0, (newlen1 + 1) * sizeof(wchar_t));
		::MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), pWch, newlen1);
		int newlen2 = ::WideCharToMultiByte(CP_UTF8, 0, pWch, -1, NULL, 0, NULL, NULL);
		char* pch = new char[newlen2 + 1];
		memset(pch, 0, (newlen2 + 1) * sizeof(char));
		::WideCharToMultiByte(CP_UTF8, 0, pWch, newlen1, pch, newlen2, NULL, NULL);
		std::string rt = pch;
		delete[]pch;
		delete[]pWch;
		return rt;
	}

	std::wstring CUtils::getAppFullpath()
	{
		std::wstring ret = L"";
		wchar_t path[MAX_PATH] = { 0 };
		GetModuleFileNameW(NULL, path, MAX_PATH);
		ret = std::wstring(path);
		return ret;
	}

	std::wstring CUtils::getFileExtension(const std::wstring & strPath)
	{
		std::wstring ret = L"";
		int length = strPath.length();
		int index = strPath.rfind(L'.');
		if (index == -1)
			return L"";
		ret = strPath.substr(index + 1, length - index - 1);
		return ret;
	}

	//去除文件的扩展名
	std::wstring CUtils::removeExtension(const std::wstring & strPath)
	{
		std::wstring ret = L"";
		int length = strPath.length();
		int index = strPath.rfind(L'.');
		if (index == -1)
			return L"";
		ret = strPath.substr(0, index);
		return ret;
	}

	std::wstring CUtils::getFileName(const std::wstring & strPath)
	{
		std::wstring ret = strPath;
		int length = strPath.length();
		int index1 = strPath.rfind(L'\\');
		int index2 = strPath.rfind(L'.');
		if (index1 == -1)
			index1 = 0;
		if (index2 == -1)
			index2 = strPath.length();
		if (index1 > index2)
			return ret;
		if (index1 != 0)
			ret = strPath.substr(index1 + 1, index2 - index1 - 1);
		else
			ret = strPath.substr(index1, index2 - index1);
		return ret;
	}

	std::wstring CUtils::getFileFolder(const std::wstring & strPath)
	{
		std::wstring ret;
		int length = strPath.length();
		int index = strPath.rfind(L'\\');
		if (index == -1)
			return L"";
		ret = strPath.substr(0, index);
		return ret;
	}

	void CUtils::copyFile(const char* src, const char* dst)
	{
		using namespace std;
		ifstream in(src, ios::binary);
		ofstream out(dst, ios::binary);
		if (!in.is_open())
		{
			exit(EXIT_FAILURE);
		}
		if (!out.is_open())
		{
			exit(EXIT_FAILURE);
		}
		if (src == dst)
		{
			exit(EXIT_FAILURE);
		}
		char buf[2048];
		long long totalBytes = 0;
		while (in)
		{
			in.read(buf, 2048);
			out.write(buf, in.gcount());
			totalBytes += in.gcount();
		}
		in.close();
		out.close();
	}

	int CUtils::createDirectory(const wchar_t* dir)
	{
		return SHCreateDirectoryExW(NULL, dir, NULL);
	}

	bool CUtils::isFileExist(const wchar_t* strPath)
	{
		if (_waccess(strPath, 0) == -1)
			return false;
		else
			return true;
	}

	bool CUtils::isFileExistA(const char* strPath)
	{
		if (_access(strPath, 0) == -1)
			return false;
		else
			return true;
	}

	void CUtils::getFiles(std::string path, std::list<std::string>& files)
	{
		//文件句柄  
		long   hFile = 0;
		//文件信息  
		struct _finddata_t fileinfo;
		std::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)
						getFiles(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);
		}
	}

	//not include path
	bool CUtils::deleteFiles(std::string path)
	{
		//文件句柄  
		long   hFile = 0;
		//文件信息  
		struct _finddata_t fileinfo;
		std::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)
					{
						deleteFiles(p.assign(path).append("\\").append(fileinfo.name));
						RemoveDirectoryA(p.assign(path).append("\\").append(fileinfo.name).c_str());
					}
				}
				else
				{
					DeleteFileA(p.assign(path).append("\\").append(fileinfo.name).c_str());
				}
			} while (_findnext(hFile, &fileinfo) == 0);
			_findclose(hFile);
		}
		//bool ret = RemoveDirectoryA(path.c_str());//如果需要删除当前目录,则去除该行注释
		return true;
	}

	//删除指定目录下的所有文件,并且删除该目录
	bool CUtils::deleteFilesEx(std::string path)
	{
		//文件句柄  
		long   hFile = 0;
		//文件信息  
		struct _finddata_t fileinfo;
		std::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)
					{
						deleteFiles(p.assign(path).append("\\").append(fileinfo.name));
						RemoveDirectoryA(p.assign(path).append("\\").append(fileinfo.name).c_str());
					}
				}
				else
				{
					DeleteFileA(p.assign(path).append("\\").append(fileinfo.name).c_str());
				}
			} while (_findnext(hFile, &fileinfo) == 0);
			_findclose(hFile);
		}
		RemoveDirectoryA(path.c_str());//如果需要删除当前目录,则去除该行注释
		return true;
	}

	bool CUtils::moveFile(std::string srcPath, std::string dstPath)
	{
		if (srcPath.empty() || dstPath.empty() || _stricmp(srcPath.c_str(), dstPath.c_str()) == 0)
			return false;
		if (isFileExistA(dstPath.c_str()))
			DeleteFileA(dstPath.c_str());
		return MoveFileA(srcPath.c_str(), dstPath.c_str())?true:false;
	}

	//格式化string
	std::string & CUtils::string_format(std::string & _str, const char * _Format, ...)
	{
		std::string tmp;
		va_list marker = NULL;
		va_start(marker, _Format);
		size_t num_of_chars = _vscprintf(_Format, marker);
		if (num_of_chars > tmp.capacity()) {
			tmp.resize(num_of_chars + 1);
		}
		vsprintf_s((char *)tmp.data(), tmp.capacity(), _Format, marker);
		va_end(marker);
		_str = tmp.c_str();
		return _str;
	}

	//格式化wstring
	std::wstring & CUtils::wstring_format(std::wstring & _str, const wchar_t * _Format, ...)
	{
		std::wstring tmp;
		va_list marker = NULL;
		va_start(marker, _Format);
		size_t num_of_chars = _vscwprintf(_Format, marker);
		if (num_of_chars > tmp.capacity()) {
			tmp.resize(num_of_chars + 1);
		}
		vswprintf_s((wchar_t *)tmp.data(), tmp.capacity(), _Format, marker);
		va_end(marker);
		_str = tmp.c_str();
		return _str;
	}

	//判断一个字符串是否为数字,十进制
	bool CUtils::isANum(std::string strNum)
	{
		for (size_t i = 0; i < strNum.size(); i++)
		{
			int tmp = (int)strNum[i];
			if (tmp >= 48 && tmp <= 57)
				continue;
			else
				return false;
		}
		return true;
	}

	//判断一个字符串是否为数字,十进制
	bool CUtils::isANum(std::wstring strNum)
	{
		for (size_t i = 0; i < strNum.size(); i++)
		{
			int tmp = (int)strNum[i];
			if (tmp >= 48 && tmp <= 57)
				continue;
			else
				return false;
		}
		return true;
	}

	//遍历path文件夹,删除指定seconds之前修改的以fileExtension结尾的文件
	bool CUtils::deleteOldFiles(std::string path, int seconds)
	{
		FILETIME ftSystemCurrent, ftSystemOld;
		SYSTEMTIME st;
		GetSystemTime(&st);
		SystemTimeToFileTime(&st, &ftSystemCurrent);
		ULARGE_INTEGER u1, offset, u2;
		u1.LowPart = ftSystemCurrent.dwLowDateTime;
		u1.HighPart = ftSystemCurrent.dwHighDateTime;
		offset.QuadPart = UInt32x32To64(seconds, 10000000);
		u2.QuadPart = u1.QuadPart - offset.QuadPart;
		ftSystemOld.dwLowDateTime = u2.LowPart;
		ftSystemOld.dwHighDateTime = u2.HighPart;

		//文件句柄  
		long   hFile = 0;
		//文件信息  
		struct _finddata_t fileinfo;
		std::string p;
		if ((hFile = _findfirst(p.assign(path).append("\\*.ini").c_str(), &fileinfo)) != -1)
		{
			do
			{
				//如果是目录,迭代之  
				//如果不是,加入列表  
				if ((fileinfo.attrib &  _A_SUBDIR))
				{
					//if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
					//{
					//	deleteOldFiles(p.assign(path).append("\\").append(fileinfo.name),seconds);
					//	RemoveDirectoryA(p.assign(path).append("\\").append(fileinfo.name).c_str());
					//}
				}
				else
				{
					std::string filePath = p.assign(path).append("\\").append(fileinfo.name);
					HANDLE handleFile = CreateFileA(filePath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
					if (INVALID_HANDLE_VALUE != handleFile)
					{
						FILETIME ftCreationTime, ftLastAccessTime, ftLastWriteTime;
						GetFileTime(handleFile, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime);
						int ret = CompareFileTime(&ftSystemOld, &ftLastWriteTime);
						if (ret == 1)//first filetime is later than second file time.
						{
							CloseHandle(handleFile);
							DeleteFileA(filePath.c_str());
						}
						else
							CloseHandle(handleFile);

					}
				}
			} while (_findnext(hFile, &fileinfo) == 0);
			_findclose(hFile);
		}
		return true;
	}
	//分割字符串
	void CUtils::SplitString(const std::string& s, std::vector<std::string>& v, const std::string& c)
	{
		std::string::size_type pos1, pos2;
		pos2 = s.find(c);
		pos1 = 0;
		while (std::string::npos != pos2)
		{
			v.push_back(s.substr(pos1, pos2 - pos1));
			pos1 = pos2 + c.size();
			pos2 = s.find(c, pos1);
		}
		if (pos1 != s.length())
		{
			v.push_back(s.substr(pos1));
		}
	}

	//分割字符串
	void CUtils::SplitWString(const std::wstring& s, std::vector<std::wstring>& v, const std::wstring& c)
	{
		std::wstring::size_type pos1, pos2;
		pos2 = s.find(c);
		pos1 = 0;
		while (std::wstring::npos != pos2)
		{
			v.push_back(s.substr(pos1, pos2 - pos1));
			pos1 = pos2 + c.size();
			pos2 = s.find(c, pos1);
		}
		if (pos1 != s.length())
		{
			v.push_back(s.substr(pos1));
		}
	}

	bool CUtils::IsTimeString(std::wstring strTime)
	{
		if (strTime.length() != 8)
			return false;
		if (strTime.at(2) != L':' || strTime.at(5) != L':')
			return false;
		std::vector<std::wstring> timeList;
		SplitWString(strTime, timeList, L":");
		if (timeList.size() != 3)
			return false;
		if (!isANum(timeList[0]) || !isANum(timeList[1]) || !isANum(timeList[2]))
			return false;
		int hour, minute, second;
		hour = std::stoi(timeList[0]);
		minute = std::stoi(timeList[1]);
		second = std::stoi(timeList[2]);
		if (hour < 0 || hour >100 || minute < 0 || minute>59 || second < 0 || second>59)
			return false;
		return true;
	}


	std::wstring& CUtils::UpperString(std::wstring& s)
	{
		transform(s.begin(), s.end(), s.begin(), ::toupper);
		return s;
	}

	std::wstring& CUtils::LowerString(std::wstring& s)
	{
		transform(s.begin(), s.end(), s.begin(), ::tolower);
		return s;
	}

	std::wstring CUtils::ToWindowSeprator(std::wstring& s)
	{
		std::replace(s.begin(), s.end(), L'/', L'\\');
		return s;
	}

	int CUtils::getFileSize(std::string& filePath)
	{
		struct _stat info;
		_stat(filePath.c_str(), &info);
		int size = info.st_size;
		return size;
	}

	//在指定文件路径写入指定信息,unicode版本
	void CLog::WriteLog(const wchar_t* filePath, const wchar_t* text)
	{
		//首先判断文件是否存在,如果不存在则创建,并在开头加入0xfeff;如果存在则直接写入
		if (_waccess(filePath, 0) == -1)
		{
			FILE* fp;
			_wfopen_s(&fp, filePath, L"wb");
			if (fp != NULL)
			{
				uint16_t wSignature = 0xFEFF;
				fwrite(&wSignature, 2, 1, fp);
				SYSTEMTIME st;
				GetLocalTime(&st);
				wchar_t buf[128] = { 0 };
				swprintf_s(buf, 128, L"%04d%02d%02d %02d:%02d:%02d:%03d	", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
				fwrite(buf, sizeof(wchar_t), wcslen(buf), fp);
				fwrite(text, sizeof(wchar_t), wcslen(text), fp);
				fwrite(L"\r\n", sizeof(wchar_t), 2, fp);
				fclose(fp);
			}
		}
		else
		{
			FILE* fp;
			_wfopen_s(&fp, filePath, L"ab");
			if (fp != NULL)
			{
				SYSTEMTIME st;
				GetLocalTime(&st);
				wchar_t buf[128] = { 0 };
				swprintf_s(buf, 128, L"%04d%02d%02d %02d:%02d:%02d:%03d	", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
				fwrite(buf, sizeof(wchar_t), wcslen(buf), fp);
				fwrite(text, sizeof(wchar_t), wcslen(text), fp);
				fwrite(L"\r\n", sizeof(wchar_t), 2, fp);
				fclose(fp);
			}
		}

	}
   

	//在指定文件路径写入指定信息,ANSI版本
	void CLog::WriteLog(const char* filePath, const char* text)
	{
		FILE* fp;
		fopen_s(&fp, filePath, "a");
		if (fp != NULL)
		{
			SYSTEMTIME st;
			GetLocalTime(&st);
			char buf[128] = { 0 };
			sprintf_s(buf, 128, "%04d%02d%02d %02d:%02d:%02d:%03d ", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
			fwrite(buf, sizeof(char), strlen(buf), fp);
			fwrite(text, sizeof(char), strlen(text), fp);
			fwrite("\r\n", sizeof(char), 2, fp);
			fclose(fp);
		}
	}

	//在指定文件路径写入指定信息,格式化字符串版本
	void CLog::WriteLogEx(const char* filePath, const char* const format, ...)
	{
		std::string tmp;
		va_list maker = NULL;
		va_start(maker, format);
		size_t numofchar = _vscprintf(format, maker);
		if (numofchar > tmp.capacity())
		{
			tmp.resize(numofchar + 1);
		}
		vsprintf_s((char*)tmp.data(), tmp.capacity(), format, maker);
		va_end(maker);
		std::string text = tmp;

		FILE* fp;
		fopen_s(&fp, filePath, "a");
		if (fp != NULL)
		{
			SYSTEMTIME st;
			GetLocalTime(&st);
			char buf[128] = { 0 };
			sprintf_s(buf, 128, "%04d%02d%02d %02d:%02d:%02d:%03d ", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
			fwrite(buf, sizeof(char), strlen(buf), fp);
			fwrite(text.c_str(), sizeof(char), text.length(), fp);
			fwrite("\r\n", sizeof(char), 2, fp);
			fclose(fp);
		}
	}
	//base64编解码
	static const std::string base64_chars =
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		"abcdefghijklmnopqrstuvwxyz"
		"0123456789+/";

	static inline bool is_base64(unsigned char c)
	{
		return (isalnum(c) || (c == '+') || (c == '/'));
	}

	std::string CBase64::base64_encode(unsigned const char* bytes_to_encode, unsigned int in_len)
	{
		std::string ret;
		int i = 0;
		int j = 0;
		unsigned char char_array_3[3];
		unsigned char char_array_4[4];
		while (in_len--)
		{
			char_array_3[i++] = *(bytes_to_encode++);
			if (i == 3)
			{
				char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
				char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
				char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
				char_array_4[3] = char_array_3[2] & 0x3f;
				for (int j = 0; j < 4; j++)
				{
					ret += base64_chars[char_array_4[j]];
				}
				i = 0;
			}
		}
		//如果字符串不是3的整数倍,则会有剩余1个字节或2个字节的情况
		if (i)
		{
			for (j = i; j < 3; j++)
				char_array_3[j] = '\0';
			char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
			char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
			char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
			char_array_4[3] = char_array_3[2] & 0x3f;

			for (j = 0; (j < i + 1); j++)
			{
				ret += base64_chars[char_array_4[j]];
			}
			while ((i++ < 3))
				ret += '=';
		}
		return ret;
	}

	std::string CBase64::base64_decode(const std::string& encoded_string)
	{
		int in_len = encoded_string.size();
		int i = 0;
		int j = 0;
		int in_ = 0;
		unsigned char char_array_4[4], char_array_3[3];
		std::string ret;

		while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
			char_array_4[i++] = encoded_string[in_]; in_++;
			if (i == 4) {
				for (i = 0; i <4; i++)
					char_array_4[i] = static_cast<unsigned char>(base64_chars.find(char_array_4[i]));

				char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
				char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
				char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

				for (i = 0; (i < 3); i++)
					ret += char_array_3[i];
				i = 0;
			}
		}

		if (i) {
			for (j = i; j <4; j++)
				char_array_4[j] = 0;

			for (j = 0; j <4; j++)
				char_array_4[j] = static_cast<unsigned char>(base64_chars.find(char_array_4[j]));

			char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
			char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
			char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];

			for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
		}

		return ret;
	}


}

test.cpp

// test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include "../Utils/utils.h"
using namespace std;
#ifdef _DEBUG
#   ifdef _UNICODE
#       pragma comment(lib, "..\\lib\\utils_d.lib")
#   else
#       pragma comment(lib, "..\\lib\\utils_dA.lib")
#   endif
#else
#   ifdef _UNICODE
#       pragma comment(lib, "..\\lib\\utils.lib")
#   else
#       pragma comment(lib, ""..\\lib\\utilsA.lib"")
#   endif
#endif


int main()
{
	string strFile = "D:\\data\\spc\\Ref_20191023101126.txt";
	// 获取文件大小
	cout << UTILS::CUtils::getFileSize(strFile);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值