C++日常用的函数总结

windows&linux
1. 检查路径是否存在
bool directory_exists(const std::string &directory)
{
   
	struct stat buffer;
	// if any condition fails
	return (stat(directory.c_str(), &buffer) == 0) && (buffer.st_mode & S_IFDIR);;
}
2. 检查文件是否存在
bool file_exists(const std::string &filename)
{
   
	struct stat buffer;
	return (stat(filename.c_str(), &buffer) == 0) && (buffer.st_mode & S_IFREG);
}
windows API 部分
1. 程序提权(提示申请使用管理员权限)
/**
 *  Creates elevated worker process.
 *
 *  \param[in] appPath path to elevated worker module
 *  \param[in] cmdLine commandline to start elevated worker with
 *
 *  \return Handle to created process.
 */
static HANDLE create_elevated_worker(PWSTR appPath, PWSTR cmdLine)
{
   
	BOOL bSuccess = FALSE;
	SHELLEXECUTEINFOW exInfo = {
    0 };

	exInfo.cbSize = sizeof(exInfo);
	exInfo.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE;
	exInfo.hwnd = NULL;
	exInfo.lpVerb = L"runas";
	exInfo.lpFile = appPath;
	exInfo.lpParameters = cmdLine;
	exInfo.lpDirectory = NULL;
	exInfo.nShow = SW_HIDE;
	/* exInfo.hInstApp is output parameter */
	/* exInfo.lpIDList, exInfo.lpClass, exInfo.hkeyClass, exInfo.dwHotKey, exInfo.DUMMYUNIONNAME
	 * are ignored for our fMask value.
	 */
	 /* exInfo.hProcess is output parameter */

	bSuccess = ShellExecuteExW(&exInfo);

	if (FALSE == bSuccess)
	{
   
		fprintf(stderr, "Failed to create worker process!\n");
		return INVALID_HANDLE_VALUE;
	}

	return exInfo.hProcess;
}
2. 获得windows下的临时文件夹(C:\Users_your_name_\AppData\Local\Temp)
static const char* get_tmp_dir()
{
   
	static char tmpdir[200] = {
    '\0' };

	if (tmpdir[0] == '\0')
	{
   
#ifndef _MSC_VER
		strcpy(tmpdir, "/tmp");
#else
		// C:\Users\houxiao1\AppData\Local\Temp
		GetTempPathA(sizeof(tmpdir) / 2, (LPSTR)tmpdir);
#endif
	}

	return tmpdir;
}
Linux 部分
1. 使用popen检查命令输出中是否包含特定字段
bool isExistInCmd(char* cmd, const char* key)
{
   
	FILE* fp = popen(cmd, "r");
	char buf[1024];

	if ((fp = popen(cmd, "r")) == NULL)
		perror("popen");

	while (fgets(buf, 1024, fp))
	{
   
		if (strstr(buf, key))
			return true;
	}

	return false;
}
2. 使用bash中模糊的匹配方式(hell*world.cpp)匹配文件路径,并返回。使用linux中的glob函数
// 返回所有满足条件的文件路径
#include <glob.h>
static bool glob_files(const std::string& pattern, std::vector<std::string>& files)
{
   
    glob_t glob_result;
    memset(&glob_result, 0, sizeof(glob_result));
    int res = glob(pattern.c_str(), GLOB_TILDE, nullptr, &glob_result);
    if (res != 0)
    {
   
        globfree(&glob_result);
        return false;
    }
    for (size_t i = 0; i < glob_result.gl_pathc; ++i) {
   
        files.emplace_back(std::string(glob_result.gl_pathv[i]));
    }
    globfree(&glob_result);
    return true;
}
3. 获取linux中可用的内存
#include <fstream>
#include <sstream>
#include <string>

//  获取linux系统可用内存
void memory_utilization(float& fmemtotal, float& fmemfree, float& fmemvalid)
{
   
    std::string memtotal;
    std::string memfree;
    std::string memavail;
    std::string membufs;
    std::string key, value;
    std::string line;
    std::ifstream stream("/proc/meminfo");

    if(stream.is_open())
    {
   
        while (std::getline(stream, line)) {
   
            std::istringstream linestream(line);
            while(linestream >> key >> value) {
   
                if (key == "Memtotal:") {
   
                    fmemtotal = std::stof(value);
                } else if(key == "MemFree:") {
   
                    fmemfree = std::stof(value);
                } else if (key == "MemAvailable:") {
   
                    fmemvalid = std::stof(value);
                }
            }
        }
    }
    stream.close();
}
字符串部分
1. 窄字符串转宽字符串
static std::wstring s2ws(const std::string& s)
{
   
	std::string curlLocale = setlocale(LC_ALL, NULL);
	setlocale(LC_ALL, "chs");
	const char* _Source = s.c_str();
	size_t _Dsize = s.size() + 1;

	wchar_t* _Dest = new wchar_t[_Dsize];
	size_t i;	
	mbstowcs_s(&i, _Dest, _Dsize, _Source, s.size());
	std::wstring result = _Dest;
	delete[] _Dest;
	setlocale(LC_ALL, curlLocale.c_str());

	return result;
}
2. TCHAR* 转string
std::string convert2string(TCHAR * STR)
{
   
	int iLen = WideCharToMultiByte(CP_ACP, 0, STR, -1, NULL, 0, NULL, NULL);
	char* chRtn = new char[iLen * sizeof(char)];
	WideCharToMultiByte(CP_ACP, 0, STR, -1, chRtn, iLen,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值