You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用_mkdir()创建目录遇无效参数错误(硬编码路径正常)

解决_mkdir() "无效参数" 错误的方案

你的问题核心是从socket接收的字符串包含隐藏的不可见字符——虽然打印输出看起来正常,但这些字符会导致路径格式非法,触发_mkdir的参数错误。以下是具体排查和修复步骤:

1. 排查隐藏的不可见字符

socket接收的字符串可能带有回车(\r,ASCII 0x0D)、换行(\n,ASCII 0x0A)或其他非打印字符,这些字符在printf输出时不会显示,但会让路径变成非法格式。

添加代码逐个检查whoami的每个字符:

for (int j = 0; whoami[j] != '\0'; j++) {
    printf("whoami[%d]: '%c' (0x%02X)\n", j, whoami[j], (unsigned char)whoami[j]);
}

如果输出中出现0x0D或0x0A,说明存在隐藏字符,需要过滤。

2. 过滤非法字符并确保字符串正确终止

在替换\为_的同时,过滤掉回车、换行等不可见字符,并且手动添加字符串终止符,避免残留无效字符:

int idx = 0;
for (int j = 0; whoami[j] != '\0'; j++) {
    // 跳过回车、换行等不可见字符
    if (whoami[j] == '\r' || whoami[j] == '\n') {
        continue;
    }
    // 替换反斜杠为下划线
    if (whoami[j] == '\\') {
        whoami[idx++] = '_';
    } else {
        whoami[idx++] = whoami[j];
    }
}
// 手动添加字符串终止符,确保格式正确
whoami[idx] = '\0';

3. 使用安全的字符串格式化函数

替换sprintf为snprintf,避免因whoami过长导致缓冲区溢出,进而损坏路径格式:

snprintf(infoPath, sizeof(infoPath), "C:\\Users\\name\\Desktop\\%s", whoami);

4. 额外检查:确认路径长度合法

Windows下路径总长度不能超过MAX_PATH(通常为260字符),如果拼接后的路径过长,也会触发错误。可以添加长度检查:

if (strlen(infoPath) >= MAX_PATH) {
    printf("Path exceeds maximum length\n");
    continue;
}

修复后的完整代码片段

char getinfo[CMP_SIZE] = "getinfo";
for (unsigned int i = 0; i < master.fd_count; i++)
{
    char infoPath[1000];

    s = master.fd_array[i];

    if (s != ListenSocket)
    {
        int r = sendStrBuffer(s, getinfo, CMP_SIZE);
        if (r == SOCKET_ERROR)
        {
            printf("error\n");
        }
                            
        char *whoami = recvStrBuffer(s);
        // 过滤隐藏字符并替换反斜杠
        int idx = 0;
        for (int j = 0; whoami[j] != '\0'; j++) {
            if (whoami[j] == '\r' || whoami[j] == '\n') {
                continue;
            }
            if (whoami[j] == '\\') {
                whoami[idx++] = '_';
            } else {
                whoami[idx++] = whoami[j];
            }
        }
        whoami[idx] = '\0';

        printf("whoami: %s\n", whoami);
        // 使用snprintf保证格式化安全
        snprintf(infoPath, sizeof(infoPath), "C:\\Users\\name\\Desktop\\%s", whoami);
        printf("infoPath: %s\n", infoPath);
                            
        // 检查路径长度是否合法
        if (strlen(infoPath) >= MAX_PATH) {
            printf("Path exceeds maximum length\n");
            continue;
        }

        if (_mkdir(infoPath) == -1)
        {
            printf("Failed to create directory: %s\n", strerror(errno));
        }
        else 
        {
            printf("Directory created successfully\n");
        }
    }
}

内容的提问来源于stack exchange,提问作者kyle walker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 13:07:42