C++常用工具函数

目录

文件相关

时间相关

字符串相关


文件相关

h文件

#pragma once

#include <string>

class FileUtil
{
public:
	/**
	 \brief 检查指定路径的文件是否存在
	 \param sFilePath 待检查文件路径
	 \return 指定路径的文件是否存在
	 \except 该函数可能抛出异常
	 \note 该函数是多线程安全的
	*/
	static bool isFileExist(const std::string & sFilePath);

	/**
	 \brief 复制文件
	 \param sSrcFilePath 待复制文件路径
	 \param sDstFilePath 目标文件路径
	 \except 该函数可能抛出异常
	 \note 该函数是多线程安全的
	*/
	static void copyFile(const std::string & sSrcFilePath, const std::string & sDstFilePath);

	/**
	 \brief 从文件路径中找出其所在的文件夹路径
	 \param sFilePath 文件路径
	 \param sSep 路径分隔符
	 \except 该函数可能抛出异常
	 \note 该函数是多线程安全的
	*/
	static std::string getDirPath(const std::string & sFilePath, 
								  const std::string & sSep);
};

cpp文件

#include "FileUtil.h"

#include <fstream>

using namespace std;

bool FileUtil::isFileExist(const string & sFilePath)
{
	using namespace std;

	if (sFilePath.empty()) {
		return false;
	} else {
		ifstream ifs(sFilePath.c_str());
		return ifs.good();
	}
}

void FileUtil::copyFile(const string & sSrcFilePath, const string & sDstFilePath)
{
	using namespace std;

	if (!isFileExist(sSrcFilePath)) {
		throw invalid_argument(("Source file doesn't exist whose path is \""
								+ sSrcFilePath + "\"").c_str());
	} else { /* do nothing */ }

	ifstream  src(sSrcFilePath, ios::binary);
	ofstream  dst(sDstFilePath, ios::binary);

	dst << src.rdbuf();
}

std::string FileUtil::getDirPath(const std::string & sFilePath,
								 const std::string & sSep)
{
	if (sFilePath.empty()) {
		throw std::runtime_error("File path is empty");
	} else if (sSep.empty()) {
		throw std::runtime_error("Path separator is empty");
	} else { /* do nothing */ }

	const auto nFndPos = sFilePath.find_last_of(sSep);
	if (std::string::npos == nFndPos) {
		return sFilePath;
	} else { /* do nothing */ }

	return sFilePath.substr(0, nFndPos + sSep.size());
}

时间相关

h文件

#pragma once

#include <string>

class TimeUtil
{
public:

	/**
	 \brief 获取当前时间的字符串
	 \return 当前时间的字符串,例如"16:55:34.155"
	 \except 该函数可能抛出异常
	 \note 该函数是多线程安全的
	*/
	static std::string currentTime();

	/**
	 \brief 获取当前时间戳的字符串
	 \return 当前时间戳的字符串
	 \except 该函数可能抛出异常
	 \note 该函数是多线程安全的
	 \note 该字符串的内容为1970年1月1日0时至今的秒数
	*/
	static std::string currentTimeStamp();
};

cpp文件

#include "TimeUtil.h"

#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>

std::string TimeUtil::currentTime()
{
	using namespace std;
	using namespace std::chrono;

	// get current time
	auto now = system_clock::now();

	// get number of milliseconds for the current second
	// (remainder after division into seconds)
	auto ms = duration_cast<milliseconds>(now.time_since_epoch()) % 1000;

	// convert to time_t in order to convert to tm (broken time)
	auto timer = system_clock::to_time_t(now);

	// convert to broken time
	#pragma warning(suppress : 4996)
	tm bt = *localtime(&timer);

	ostringstream oss;

	oss << put_time(&bt, "%H:%M:%S"); // HH:MM:SS
	oss << '.' << setfill('0') << setw(3) << ms.count();

	return oss.str();
}

std::string TimeUtil::currentTimeStamp()
{
	using namespace std;

	time_t t = std::time(0);
	ostringstream oss;
	oss << t;
	return oss.str();
}

字符串相关

h文件

#pragma once

#include <string>

class StringUtil
{
public:
	/**
	 \brief 获取当前的locale信息
	 \return 当前的locale信息
	 \except 该函数可能抛出异常
	 \note 该函数是多线程安全的
	*/
	static const std::string & currentLocale();

	/**
	 \brief 将utf8编码字符串转成本地编码的字符串
	 \param pSrcStr 待转换的utf8编码字符串
	 \return 本地编码的字符串
	 \except 该函数可能抛出异常
	 \note 该函数是多线程安全的
	*/
	static const std::string utf8ToLocalStr(const char *pSrcStr) noexcept(false);

	/**
	 \brief 将本地编码字符串转成utf8编码的字符串
	 \param pSrcStr 待转换的本地编码字符串
	 \return utf编码的字符串
	 \except 该函数可能抛出异常
	 \note 该函数是多线程安全的
	*/
	static const std::string localStrToUTF8(const char *pSrcStr) noexcept(false);
};

cpp文件

#include "StringUtil.h"

#include <atomic>
#include <codecvt>
#include <locale>
#include <vector>

const std::string & StringUtil::currentLocale()
{
	static std::string sCurLoc;
	static std::atomic_bool bInit{ false };
	if (bInit) return sCurLoc;
	bInit = true;
	setlocale(LC_ALL, "");
	sCurLoc = setlocale(LC_ALL, NULL);
	return sCurLoc;
}

const std::string StringUtil::utf8ToLocalStr(const char * pSrcStr) noexcept(false)
{
	const std::string strUtf8(pSrcStr);
	std::wstring_convert<std::codecvt_utf8<wchar_t>> cutf8;
	std::wstring wTemp = cutf8.from_bytes(strUtf8);

	const auto & curLoc = currentLocale();
	if (std::string::npos != curLoc.find("UTF-8")) return pSrcStr;
	std::locale loc(curLoc);
	const wchar_t* pwszNext = nullptr;
	char* pszNext = nullptr;
	mbstate_t state = {};

	std::vector<char> buff(wTemp.size() * 2);
	int res = std::use_facet < std::codecvt<wchar_t, char, mbstate_t> >
		(loc).out(state,
				  wTemp.data(), wTemp.data() + wTemp.size(), pwszNext,
				  buff.data(), buff.data() + buff.size(), pszNext);

	if (std::codecvt_base::ok != res) {
		throw std::runtime_error(("Fail to convert UTF8 string to local string, string is "
								  + std::string(pSrcStr)).c_str());
	} else { /* Do nothing */ }
	return std::string(buff.data(), pszNext);
}

const std::string StringUtil::localStrToUTF8(const char * pSrcStr) noexcept(false)
{
	const std::string sSrcStr(pSrcStr);
	std::vector<wchar_t> buff(sSrcStr.size());
	const auto & curLoc = currentLocale();
	if (std::string::npos != curLoc.find("UTF-8")) return pSrcStr;
	std::locale loc(curLoc);
	wchar_t* pwszNext = nullptr;
	const char* pszNext = nullptr;
	mbstate_t state = {};
	int res = std::use_facet < std::codecvt<wchar_t, char, mbstate_t>>
		(loc).in(state,
				 sSrcStr.data(), sSrcStr.data() + sSrcStr.size(), pszNext,
				 buff.data(), buff.data() + buff.size(), pwszNext);
	if (std::codecvt_base::ok != res) {
		throw std::runtime_error(("Fail to convert UTF8 string to local string, string is "
							 + std::string(pSrcStr)).c_str());
	} else { /* Do nothing */ }

	std::wstring_convert<std::codecvt_utf8<wchar_t>> cutf8;
	return cutf8.to_bytes(std::wstring(buff.data(), pwszNext));
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值