c++编程常用函数备份

检测cpu内核的数目:

int core_count()
{
	SYSTEM_INFO si;
	GetSystemInfo(&si);
	int count = si.dwNumberOfProcessors;
	return count;
}

在开发过程中,难免要对程序的效率进行检测,这时就要统计程序的运行时间,下面代码给出了c++中如何输出系统的时间

方法一:

int get_sys_time() 
{ 
    time_t time_seconds = time(0); 
    struct tm now_time; 
    localtime_s(&now_time, &time_seconds); 
    std::cout << “current time: “; 
    printf(“%d-%d-%d %d:%d:%d\n”, now_time.tm_year + 1900, now_time.tm_mon + 1, now_time.tm_mday, now_time.tm_hour, now_time.tm_min, now_time.tm_sec); 
    return 0; 
}

方法2:

int get_sys_time()
{
    time_t t;
    time(&t);
    printf("%s", ctime(&t));
    return 0;
}

字符串分割函数

/**
@str 待分割的字符串
@pattern 分割符
@return 返回字符串类型的容器
*/
vector<string> split(const string &str,const string &pattern)
{
    //const char* convert to char*
    char * strc = new char[strlen(str.c_str())+1];
    strcpy(strc, str.c_str());
    vector<string> resultVec;
    char* tmpStr = strtok(strc, pattern.c_str());
    while (tmpStr != NULL)
    {
        resultVec.push_back(string(tmpStr));
        tmpStr = strtok(NULL, pattern.c_str());
    }
    delete[] strc;
    return resultVec;
}

遍历文件夹下的文件

需添加头文件
#include <windows.h>
#include <io.h>
void getFilesAll(string dirpath, vector<string>& files)
{
	//文件句柄 
	intptr_t  hFile = 0;
	//文件信息 
	struct _finddata_t fileinfo;
	string p;
	if ((hFile = _findfirst(p.assign(dirpath).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) );
					getFilesAll(p.assign(dirpath).append("\\").append(fileinfo.name), files);
				}
			}
			else
			{
				files.push_back(p.assign(dirpath).append("\\").append(fileinfo.name));
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}

LPCWSTR stringToLPCWSTR(std::string orig)
{
	size_t origsize = orig.length() + 1;
	const size_t newsize = 100;
	size_t convertedChars = 0;
	wchar_t *wcstring = (wchar_t *)malloc(sizeof(wchar_t)*(orig.length() - 1));
	mbstowcs_s(&convertedChars, wcstring, origsize, orig.c_str(), _TRUNCATE);
	return wcstring;
}

判断是否为文件还是文件夹
需添加头文件#include <io.h>

bool IsDirectory(const char * pszFilePath)
{
	DWORD dwAttr = GetFileAttributes(stringToLPCWSTR(pszFilePath));
	if (dwAttr & FILE_ATTRIBUTE_DIRECTORY)
	{//是目录
		return true;
	}
	else
	{//是文件
		return false;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三月微暖寻春笋

赠人玫瑰手有余香

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值