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

如何将char*转换为宽字符串以用于FindFirstFile函数?

Solution to Convert Char* to LPCWSTR for FindFirstFile

Hey there! Let's break down your issues and fix them one by one:

Key Problems in Your Code

  • Invalid Type Cast: Casting char* directly to LPCWSTR doesn't convert the string's encoding—it just forces the compiler to treat a byte array as wide characters, which leads to garbage data and failed file searches.
  • C Struct Initialization Error: In standard C, you can't initialize a struct member like char* str = NULL; directly in the struct definition. That's a C++ feature, so we need to adjust this for C compatibility.
  • Missing Encoding Conversion: FindFirstFile (when using Unicode mode, which is default in modern Windows) requires a UTF-16 wide string, but your input is a multi-byte char string.

Step-by-Step Fixes

1. Correct the Struct Definition

Update your struct to follow standard C syntax:

struct drtctrAr {
    char* str; // Remove inline initialization here
};

Then explicitly initialize the member when declaring the variable:

struct drtctrAr drctr;
drctr.str = NULL; // Set pointer to NULL to avoid undefined behavior

2. Convert Multi-Byte String to Wide String

Use the Windows API MultiByteToWideChar to safely convert your char* path to a wchar_t* (which is compatible with LPCWSTR). This function handles the actual encoding conversion instead of just type casting.

3. Proper Memory Management

Add checks for memory allocation failures and make sure to free all allocated memory to avoid leaks.

Corrected Full Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>

// Fixed struct definition for C
struct drtctrAr {
    char* str;
};

int main() {
    system("chcp 1251");
    char tmpstr[1000];
    struct drtctrAr drctr;
    drctr.str = NULL; // Initialize pointer to NULL
    int mbLen;
    wchar_t* widePath = NULL;
    int wideLen;

    printf("Please enter the directory: ");
    gets_s(tmpstr, 1000);

    // Allocate and copy multi-byte input string
    mbLen = strlen(tmpstr) + 1;
    drctr.str = (char*)malloc(sizeof(char) * mbLen);
    if (drctr.str == NULL) {
        printf("Memory allocation failed for input string!\n");
        return 1;
    }
    strcpy_s(drctr.str, mbLen, tmpstr);

    // Calculate required length for wide string
    wideLen = MultiByteToWideChar(CP_ACP, 0, drctr.str, -1, NULL, 0);
    if (wideLen == 0) {
        printf("Failed to calculate wide string length! Error: %d\n", GetLastError());
        free(drctr.str);
        return 1;
    }

    // Allocate memory for wide string
    widePath = (wchar_t*)malloc(sizeof(wchar_t) * wideLen);
    if (widePath == NULL) {
        printf("Memory allocation failed for wide string!\n");
        free(drctr.str);
        return 1;
    }

    // Perform actual conversion from multi-byte to wide
    if (!MultiByteToWideChar(CP_ACP, 0, drctr.str, -1, widePath, wideLen)) {
        printf("String conversion failed! Error: %d\n", GetLastError());
        free(drctr.str);
        free(widePath);
        return 1;
    }

    // Use wide string with FindFirstFileW (explicit Unicode version)
    WIN32_FIND_DATAW FindFileData;
    HANDLE hf = FindFirstFileW(widePath, &FindFileData);
    if (hf == INVALID_HANDLE_VALUE) {
        printf("Error opening files or no files found! Error: %d\n", GetLastError());
        free(drctr.str);
        free(widePath);
        return 1;
    } else {
        do {
            printf("Found file: %ls\n", FindFileData.cFileName);
        } while (FindNextFileW(hf, &FindFileData) != 0);
        FindClose(hf);
    }

    // Clean up all allocated memory
    free(drctr.str);
    free(widePath);

    return 0;
}

Explanations

  • MultiByteToWideChar: We use CP_ACP (ANSI Code Page) here because you set the console to code page 1251, ensuring the conversion matches your input encoding.
  • Explicit Unicode Functions: Using FindFirstFileW and WIN32_FIND_DATAW removes ambiguity about which string type we're working with.
  • Error Checking: Added checks for memory allocation and API failures to help you debug issues if they occur.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:04:10