c++造轮子

标准化windows路径

bool NormalizePath(const std::string &in, std::string &out)
{
    char *rs = (char *)malloc(in.length() + 1);
    if (rs == NULL) {
        return false;
    }
    char *p = rs;
    for (int i = 0; i < in.length(); i++) {
        if (in[i] != '\\' && in[i] != '/') {
            *p++ = in[i];
        } else if (i == 0 || (in[i - 1] != '\\' && in[i - 1] != '/')) {
            *p++ = '\\';
        }    
    }
    *p = '\0';
    out = std::string(rs);
    free(rs);
    return true;
}

判断目录是否存在(windows)

bool DirectoryExists(std::string dirPath) {
	DWORD attribs = GetFileAttributesA(dirPath.c_str());
	if (attribs == INVALID_FILE_ATTRIBUTES) {
		return false;
	}
	return (attribs & FILE_ATTRIBUTE_DIRECTORY);
}

按层级依次创建所有目录(windows)

bool CreateAllDir(std::string dir)
{
    if (dir == "") {
        printf("dir is empty!\n");
        return false;
    }
    for (int i = 0; i < dir.length(); i++) {
        if (dir[i] == '\\') {
            std::string curDir = dir.substr(0, i);
            if (!DirectoryExists(curDir)) {
                if (!CreateDirectoryA(curDir.c_str(), NULL) && (GetLastError() != ERROR_ALREADY_EXISTS)) {
                    return false;
                }
            }
        }
    }
    return true;
}

读写注册表(windows)

bool WriteRegistryString(HKEY hKeyRoot, const std::string& subKey, const std::string& valueName, const std::string& value) {
    HKEY hKey;
    if (ERROR_SUCCESS != RegCreateKeyExA(hKeyRoot, subKey.c_str(), 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL)) {
        return false;
    }

    int result = RegSetValueExA(hKey, valueName.c_str(), 0, REG_SZ, (BYTE*)value.c_str(), value.length() + 1);
    RegCloseKey(hKey);
    return result == ERROR_SUCCESS;
}


std::string ReadRegistryString(HKEY hKeyRoot, const std::string& subKey, const std::string& valueName) {
    HKEY hKey;
    if (ERROR_SUCCESS != RegOpenKeyExA(hKeyRoot, subKey.c_str(), 0, KEY_READ, &hKey)) {
        return "";
    }

    // 获取值大小
    DWORD dataSize = 0;
    long result = RegQueryValueExA(hKey, valueName.c_str(), nullptr, nullptr, nullptr, &dataSize);
    if (result != ERROR_SUCCESS || dataSize == 0) {
        RegCloseKey(hKey);
        return "";
    }

    // 读取值数据
    std::vector<char> buffer(dataSize);
    result = RegQueryValueExA(hKey, valueName.c_str(), nullptr, nullptr, (LPBYTE)(buffer.data()), &dataSize);
    RegCloseKey(hKey);

    if (result == ERROR_SUCCESS) {
        return std::string(buffer.data());
    }
    return "";
}

将字符串写入剪切板(windows)

void SetClipLTY(const std::string& str)
{
    char* clipBoardData = (char*)malloc(str.length() + 1);
    if (clipBoardData == NULL) {
        printf("malloc failed!\n");
        return;
    }
    strcpy(clipBoardData, str.c_str());

    OpenClipboard(NULL);
    EmptyClipboard();
    SetClipboardData(CF_TEXT, (HANDLE)clipBoardData);
    CloseClipboard();
    free(clipBoardData);
}
posted @ 2025-04-19 18:58  肉肉的男朋友  阅读(11)  评论(0)    收藏  举报