C/C++ 常用的函数与方法

1,创建多级目录

#include <string>
#include <direct.h> //_mkdir函数的头文件
#include <io.h>     //_access函数的头文件
using namespace std;
void CreateDir( const char *dir )
{
    int m = 0, n;
    string str1, str2;
    str1 = dir;
    str2 = str1.substr( 0, 2 );
    str1 = str1.substr( 3, str1.size() );
    while( m >= 0 )
    {
        m = str1.find('\\');
    
        str2 += '\\' + str1.substr( 0, m );    
        n = _access( str2.c_str(), 0 ); //判断该目录是否存在
        if( n == -1 )
        {
            _mkdir( str2.c_str() );     //创建目录
        }
        
        str1 = str1.substr( m+1, str1.size() );
    }
}
int main(int argc, char* argv[])
{
    char dir[] = "E:\\Demo\\Folder\\subFolder\\my";
    CreateDir( dir );
    return 0;
}
//或者使用WinAPI
MakeSureDirectoryPathExists

2,获取exe所在目录

#include <Windows.h>
#include <atlstr.h>
void GetExePath(char *pBuffer)
{
    GetModuleFileNameA(NULL,(LPSTR)pBuffer,MAX_PATH);
    PathRemoveFileSpecA(pBuffer);
}

3,不区分大小写的strstr

const char * stristr(const char * str1,const char * str2)
{
	char *cp = (char *)str1;
	char *s1, *s2;
	if (!*str2)
		return((char *)str1);
	while (*cp)
	{
		s1 = cp;
		s2 = (char *)str2;
		while (*s1 && *s2 && (!(*s1 - *s2) || !(*s1 - *s2 - 32) || !(*s1 - *s2 + 32))) {
			s1++, s2++;
		}
		if (!*s2)
			return(cp);
		cp++;
	}
	return nullptr;
}

4,wstring转string

std::string ConvertWStringToAnsi(std::wstring wstr)
{
	std::string result;
	int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
	if (len <= 0)
		return result;
	char* buffer = new char[len + 1];
	if (buffer == NULL)
		return result;
	WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
	buffer[len] = '\0';               //字符串断尾
	result.append(buffer);            //赋值
	delete[] buffer;                  //删除缓冲区
	return result;
}

5,string转wstring

std::wstring ConvertAnsiToWString(std::string str)
{
	std::wstring result;

	int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);
	if (len < 0)
		return result;

	wchar_t* buffer = new wchar_t[len + 1];
	if (buffer == NULL)
		return result;

	MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);

	buffer[len] = '\0';                    //字符串断尾
	result.append(buffer);                 //赋值
	delete[] buffer;                       //删除缓冲区
	return result;
}

6,获取注册表值

std::string GetRegValue(int nKeyType, const std::string& strUrl, const std::string& strKey)
{
	std::string strValue("");
	HKEY hKey = NULL;
	HKEY  hKeyResult = NULL;
	DWORD dwSize = 0;
	DWORD dwDataType = 0;
	std::string wstrUrl = strUrl;
	std::string wstrKey = strKey;

	switch (nKeyType)
	{
	case 0:
	{
		hKey = HKEY_CLASSES_ROOT;
		break;
	}
	case 1:
	{
		hKey = HKEY_CURRENT_USER;
		break;
	}
	case 2:
	{
		hKey = HKEY_LOCAL_MACHINE;
		break;
	}
	case 3:
	{
		hKey = HKEY_USERS;
		break;
	}
	case 4:
	{
		hKey = HKEY_PERFORMANCE_DATA;
		break;
	}
	case 5:
	{
		hKey = HKEY_CURRENT_CONFIG;
		break;
	}
	case 6:
	{
		hKey = HKEY_DYN_DATA;
		break;
	}
	case 7:
	{
		hKey = HKEY_CURRENT_USER_LOCAL_SETTINGS;
		break;
	}
	case 8:
	{
		hKey = HKEY_PERFORMANCE_TEXT;
		break;
	}
	case 9:
	{
		hKey = HKEY_PERFORMANCE_NLSTEXT;
		break;
	}
	default:
	{
		return strValue;
	}
	}

	//打开注册表
	if (ERROR_SUCCESS == ::RegOpenKeyEx(hKey, wstrUrl.c_str(), 0, KEY_QUERY_VALUE, &hKeyResult))
	{
		// 获取缓存的长度dwSize及类型dwDataType
		::RegQueryValueEx(hKeyResult, wstrKey.c_str(), 0, &dwDataType, NULL, &dwSize);
		switch (dwDataType)
		{
		case REG_MULTI_SZ:
		{
			//分配内存大小
			BYTE* lpValue = new BYTE[dwSize];
			//获取注册表中指定的键所对应的值
			LONG lRet = ::RegQueryValueEx(hKeyResult, wstrKey.c_str(), 0, &dwDataType, lpValue, &dwSize);
			delete[] lpValue;
			break;
		}
		case REG_SZ:
		{
			//分配内存大小
			char * lpValue = new char[dwSize];
			memset(lpValue, 0, dwSize);
			//获取注册表中指定的键所对应的值
			if (ERROR_SUCCESS == ::RegQueryValueEx(hKeyResult, wstrKey.c_str(), 0, &dwDataType, (LPBYTE)lpValue, &dwSize))
			{
				strValue = lpValue;
			}
			delete lpValue;
			break;
		}
		default:
			break;
		}
	}	//关闭注册表
	::RegCloseKey(hKeyResult);
	return strValue;
}

7,设置注册表值


bool SetRegStrValue(HKEY type,const char *pLocation, const char * szItem,const char * szWriteKey,const char*szValue)
{
	HKEY hkey;//定义有关的hkey,在查询结束时要关闭  
	HKEY hTempKey;
	bool bValue = true;

	if (ERROR_SUCCESS == RegOpenKeyEx(type, pLocation, 0, KEY_SET_VALUE, &hkey))
	{
		if (ERROR_SUCCESS == ::RegCreateKey(hkey, szItem, &hTempKey))
		{
			if (ERROR_SUCCESS != ::RegSetValueEx(hTempKey, szWriteKey, 0, REG_SZ, (CONST BYTE*)szValue, strlen(szValue)+1))
			{
				bValue = false;
			}
		}
	}
	::RegCloseKey(hkey);
	return bValue;
}

8,拆分字符串

std::vector<std::string> splitString(std::string srcStr, std::string delimStr,bool repeatedCharIgnored)
{
    std::vector<std::string> resultStringVector;
    std::replace_if(srcStr.begin(), srcStr.end(), [&](const char& c){if(delimStr.find(c)!=std::string::npos){return true;}else{return false;}}/*pred*/, delimStr.at(0));//将出现的所有分隔符都替换成为一个相同的字符(分隔符字符串的第一个)
    size_t pos=srcStr.find(delimStr.at(0));
    std::string addedString="";
    while (pos!=std::string::npos) {
        addedString=srcStr.substr(0,pos);
        if (!addedString.empty()||!repeatedCharIgnored) {
            resultStringVector.push_back(addedString);
        }
        srcStr.erase(srcStr.begin(), srcStr.begin()+pos+1);
        pos=srcStr.find(delimStr.at(0));
    }
    addedString=srcStr;
    if (!addedString.empty()||!repeatedCharIgnored) {
        resultStringVector.push_back(addedString);
    }
    return resultStringVector;
}

9,GBK转UTF-8,vs编译的dll给Qt来调用,需要转一个字符集

std::string GBKToUTF8(const std::string& strGBK)
{
    std::string strOutUTF8 = "";
    WCHAR * str1;
    int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
    str1 = new WCHAR[n];
    MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);
    n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
    char * str2 = new char[n];
    WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
    strOutUTF8 = str2;
    delete[]str1;
    str1 = NULL;
    delete[]str2;
    str2 = NULL;
    return strOutUTF8;
}

10,字符串替换

void string_replace( std::string &strBig, const std::string &strsrc, const std::string &strdst )
{
 std::string::size_type pos = 0;
 std::string::size_type srclen = strsrc.size();
 std::string::size_type dstlen = strdst.size();
 
 while( (pos=strBig.find(strsrc, pos)) != std::string::npos )
 {
  strBig.replace( pos, srclen, strdst );
  pos += dstlen;
 }
} 

11,好用的执行cmd命令

#include <windows.h>

#include <iostream>  
#include <corecrt_io.h>
using namespace std;
// 描述:execmd函数执行命令,并将结果存储到result字符串数组中   
// 参数:cmd表示要执行的命令  
// result是执行的结果存储的字符串数组  
// 函数执行成功返回1,失败返回0    
int execmd(const char* cmd, char* result) {
	char buffer[128];                         //定义缓冲区                          
	FILE* pipe = _popen(cmd, "r");            //打开管道,并执行命令   
	if (!pipe)
		return 0;                      //返回0表示运行失败   

	while (!feof(pipe)) {
		if (fgets(buffer, 128, pipe)) {             //将管道输出到result中   
			strcat(result, buffer);
		}
	}
	_pclose(pipe);                            //关闭管道   
	return 1;                                 //返回1表示运行成功   
}

int main()
{
	char buffer[1024] = {0};
	if (1 == execmd("netsh winsock reset", buffer))
	{
		printf(buffer);
	}
	else
	{
		::MessageBox(NULL,L"",L"",NULL);
	}
    return 0;
}

12,删除所有目录

BOOL IsDirectory(const char *pDir)
{
	char szCurPath[500];
	ZeroMemory(szCurPath, 500);
	sprintf_s(szCurPath, 500, "%s//*", pDir);
	WIN32_FIND_DATAA FindFileData;
	ZeroMemory(&FindFileData, sizeof(WIN32_FIND_DATAA));

	HANDLE hFile = FindFirstFileA(szCurPath, &FindFileData); /**< find first file by given path. */

	if (hFile == INVALID_HANDLE_VALUE)
	{
		FindClose(hFile);
		return FALSE; /** 如果不能找到第一个文件,那么没有目录 */
	}
	else
	{
		FindClose(hFile);
		return TRUE;
	}
}

BOOL DeleteDirectory(const char * DirName)
{
	char szCurPath[MAX_PATH];        //用于定义搜索格式
	_snprintf(szCurPath, MAX_PATH, "%s\\*.*", DirName);    //匹配格式为*.*,即该目录下的所有文件
	WIN32_FIND_DATAA FindFileData;
	ZeroMemory(&FindFileData, sizeof(WIN32_FIND_DATAA));
	HANDLE hFile = FindFirstFileA(szCurPath, &FindFileData);
	BOOL IsFinded = TRUE;
	while (IsFinded)
	{
		IsFinded = FindNextFileA(hFile, &FindFileData);    //递归搜索其他的文件
		if (strcmp(FindFileData.cFileName, ".") && strcmp(FindFileData.cFileName, "..")) //如果不是"." ".."目录
		{
			std::string strFileName = "";
			strFileName = strFileName + DirName + "\\" + FindFileData.cFileName;
			std::string strTemp;
			strTemp = strFileName;
			if (IsDirectory(strFileName.c_str())) //如果是目录,则递归地调用
			{
				printf("目录为:%s/n", strFileName.c_str());
				DeleteDirectory(strTemp.c_str());
			}
			else
			{
				DeleteFileA(strTemp.c_str());
			}
		}
	}
	FindClose(hFile);

	BOOL bRet = RemoveDirectoryA(DirName);
	if (bRet == 0) //删除目录
	{
		printf("删除%s目录失败!/n", DirName);
		return FALSE;
	}
	return TRUE;
}

或者使用Shlwapi ,包含Shlwapi.lib
*通过调用ShFileOperation来实现整个目录的删除*/
/*只删除单个目录*/
BOOL SHDeleteFolder(LPCTSTR pstrFolder, BOOL bAllowUndo)
{
    if ((NULL == pstrFolder))
    {
        return FALSE;
    }

    int iPathLen = _tcslen(pstrFolder);
    if (iPathLen >= MAX_PATH)
    {
        return FALSE;
    }

    /*确保目录的路径以2个\0结尾*/
    TCHAR tczFolder[MAX_PATH+1];
    ZeroMemory(tczFolder, (MAX_PATH+1)*sizeof(TCHAR));
    _tcscpy(tczFolder, pstrFolder);
    tczFolder[iPathLen] = _T('\0');
    tczFolder[iPathLen+1] = _T('\0');

    SHFILEOPSTRUCT FileOp; 
    ZeroMemory(&FileOp, sizeof(SHFILEOPSTRUCT)); 
    FileOp.fFlags |= FOF_SILENT;        /*不显示进度*/
    FileOp.fFlags |= FOF_NOERRORUI;        /*不报告错误信息*/
    FileOp.fFlags |= FOF_NOCONFIRMATION;/*直接删除,不进行确认*/
    FileOp.hNameMappings = NULL;
    FileOp.hwnd = NULL;
    FileOp.lpszProgressTitle = NULL;
    FileOp.wFunc = FO_DELETE;
    FileOp.pFrom = tczFolder;            /*要删除的目录,必须以2个\0结尾*/
    FileOp.pTo = NULL; 

    /*根据传递的bAllowUndo参数确定是否删除到回收站*/
    if (bAllowUndo)
    {   
        FileOp.fFlags |= FOF_ALLOWUNDO; /*删除到回收站*/
    }  
    else  
    {   
        FileOp.fFlags &= ~FOF_ALLOWUNDO; /*直接删除,不放入回收站*/
    }
    
    /*删除目录*/
    if (0 == SHFileOperation(&FileOp))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

13,copy目录下所有文件到另一个目录下

void CopyFiles(const char* lpPath, const char *pFolder)
{
	char szFind[MAX_PATH] = { 0 };
	WIN32_FIND_DATA FindFileData;

	strcpy(szFind, lpPath);
	strcat(szFind, "\\*.*");

	HANDLE hFind = ::FindFirstFile(szFind, &FindFileData);
	if (INVALID_HANDLE_VALUE == hFind)    return;

	while (true)
	{
		if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if (FindFileData.cFileName[0] != '.')
			{
				char szFile[MAX_PATH];
				strcpy(szFile, lpPath);
				strcat(szFile, (char*)(FindFileData.cFileName));
				CopyFiles(szFile, pFolder);
			}
		}
		else
		{
			//std::cout << FindFileData.cFileName << std::endl;
			std::string strTemp = lpPath;
			strTemp += FindFileData.cFileName;
		

			std::string strDest = pFolder;
			strDest += FindFileData.cFileName;

			CopyFileA(strTemp.c_str(), strDest.c_str(), FALSE);
		}
		if (!FindNextFile(hFind, &FindFileData))    break;
	}
	FindClose(hFind);
}

程序实现自删除


#include<windows.h>  
#include<ShlObj.h>  
#include <tchar.h>  
#include <shellapi.h>


VOID DelItself()
{
	SHELLEXECUTEINFO stShellDel;
	TCHAR szBat[MAX_PATH];

	//获取文件路径名  
	TCHAR szFileName[MAX_PATH], szComspec[MAX_PATH];
	if ((GetModuleFileName(0, szFileName, MAX_PATH) != 0) &&
		(GetShortPathName(szFileName, szFileName, MAX_PATH) != 0) &&
		(GetEnvironmentVariable("COMSPEC", szComspec, MAX_PATH) != 0))
	{
		lstrcpy(szBat, "/c del ");
		lstrcat(szBat, szFileName);
		lstrcat(szBat, " > nul");

		stShellDel.cbSize = sizeof(stShellDel);

		//命令窗口进程句柄,ShellExecuteEx函数执行时设置。   
		stShellDel.hwnd = 0;
		stShellDel.lpVerb = "Open";
		stShellDel.lpFile = szComspec;
		stShellDel.lpParameters = szBat;
		stShellDel.lpDirectory = NULL;
		stShellDel.nShow = SW_HIDE;

		//设置为SellExecuteEx函数结束后进程退出。   
		stShellDel.fMask = SEE_MASK_NOCLOSEPROCESS;

		//创建执行命令窗口进程。   
		if (ShellExecuteEx(&stShellDel))
		{
			//设置命令行进程的执行级别为空闲执行,这使本程序有足够的时间从内存中退出。   
			SetPriorityClass(stShellDel.hProcess, IDLE_PRIORITY_CLASS);

			//设置本程序进程的执行级别为实时执行,这保证本程序能立即获取CPU执行权,快速退出。   
			SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
			SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);

			//通知Windows资源管理器,本程序文件已经被删除。   
			SHChangeNotify(SHCNE_DELETE, SHCNF_PATH, szFileName, 0);
			ExitProcess(0);
		}
	}

}

清空目录

BOOL EmptyDirectory(const char * lpszPath)
{
	SHFILEOPSTRUCT FileOp;
	ZeroMemory((void *)& FileOp, sizeof(SHFILEOPSTRUCT));
	FileOp.fFlags = FOF_NOCONFIRMATION | FOF_SILENT;
	FileOp.hNameMappings = NULL;
	FileOp.hwnd = NULL;
	FileOp.lpszProgressTitle = NULL;
	char tempPath[256] = { 0 };
	//使用通配符
	memcpy(tempPath, lpszPath, strlen(lpszPath)); memcpy(&tempPath[strlen(lpszPath)], "//*", strlen("//*"));
	FileOp.pFrom =tempPath;
	FileOp.pTo = NULL;
	FileOp.wFunc = FO_DELETE;
	return SHFileOperation(&FileOp) == 0;
}

copy 目录

void copydir(char* src, char* dst)
{
	WIN32_FIND_DATAA FindFileData;
	HANDLE hFind;
	char tmpsrc[256];
	strcpy(tmpsrc, src);
	strcat(tmpsrc, "\\*.*");
	hFind = FindFirstFileA(tmpsrc, &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE)
		return;
	CreateDirectoryA(dst, 0);
	do
	{
		char newdst[256];
		strcpy(newdst, dst);
		if (newdst[strlen(newdst)] != '\\')
			strcat(newdst, "\\");
		strcat(newdst, FindFileData.cFileName);


		char newsrc[256];
		strcpy(newsrc, src);
		if (newsrc[strlen(newsrc)] != '\\')
			strcat(newsrc, "\\");
		strcat(newsrc, FindFileData.cFileName);
		if (FindFileData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
		{
			if (strcmp(FindFileData.cFileName, ".") != 0 && strcmp(FindFileData.cFileName, "..") != 0)
			{
				copydir(newsrc, newdst);
			}
		}
		else
		{
			CopyFileA(newsrc, newdst, false);
		}
	} while (FindNextFileA(hFind, &FindFileData));
	FindClose(hFind);
}	std::string strDest = pFolder;
			strDest += FindFileData.cFileName;

			CopyFileA(strTemp.c_str(), strDest.c_str(), FALSE);
		}
		if (!FindNextFileA(hFind, &FindFileData))    break;
	}
	FindClose(hFind);
}

去除文件目录文件名

1、完整路径,去除后缀名   PathRemoveExtensionA

[cpp] view plain copy
#include <iostream>//cout函数所需  
#include "atlstr.h"  //PathRemoveExtensionA函数所需  
  
using namespace std;  
  
void main(void)  
{  
    char buffer_1[] = "C:\\TEST\\sample.txt";  
    char *lpStr1;  
    lpStr1 = buffer_1;  
    cout << "The path with extension is          : " << lpStr1 << endl;  
    PathRemoveExtensionA(lpStr1);  
    cout << "\nThe path without extension is       : " << lpStr1 << endl;  
    system("pause");  
}  
OUTPUT:
==================
The path with extension is          : C:\TEST\sample.txt
The path without extension is       : C:\TEST\sample

2、完整文件路径,获得目录

[cpp] view plain copy
#include <iostream>//cout函数所需  
#include "atlstr.h"  //PathRemoveFileSpecA函数所需  
  
using namespace std;  
  
void main(void)  
{  
    char buffer_1[] = "C:\\TEST\\sample.txt";  
    char *lpStr1;  
    lpStr1 = buffer_1;  
    cout << "The path with file spec is          : " << lpStr1 << endl;  
    PathRemoveFileSpecA(lpStr1);  
    cout << "\nThe path without file spec is       : " << lpStr1 << endl;  
    //注意如果获得了目录,需要得到另一个文件路径时  
    string filename = lpStr1;  
    filename = filename + "\\samle.txt";  
    system("pause");  
}  
OUTPUT:
==================
The path with file spec is          : C:\TEST\sample.txt
The path without file spec is       : C:\TEST

清空目录的示例:

 // Delete szSrcFile next time system is rebooted   MoveFileEx(szSrcFile, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值