首页 > 解决方案 > 如何将 char* 转换为长字符串以在 FindFirstFile 函数中使用它?

问题描述

我为搜索目录设置了 char* 数组,以便用户可以输入查找文件的位置,并且 FindFirstFile 函数应该使用它。我已经发现,如果您在代码中设置搜索目录,您只需在“文本”之前添加“L”即可进行转换。但是如何使它将常规字符串转换为长字符串呢?它说它需要 LPCWSTR 作为输入,但如果我只是尝试用 (LPCWSTR) 转换它,它不会找到任何文件。然而,我在处理数组本身时也可能做错了什么,因为我在编码方面是个菜鸟,并且有时会犯这些错误

我也知道 C 中字符串的那些不同结构,但我不允许在这个项目中使用任何面向对象的编程,所以我必须坚持这一点

struct drtctrAr
{
    char* str = NULL;
}; 

int main()
{
    system("chcp 1251");

    char tmpstr[1000];
    drtctrAr drctr;
    int len;
    
    printf("Please enter the directory: ");
    gets_s(tmpstr, 1000);

    len = strlen(tmpstr)+1;
    drctr.str = (char*)malloc(sizeof(char) * len);
    strcpy_s(drctr.str, len, tmpstr);

    WIN32_FIND_DATA FindFileData;
    HANDLE hf;

    hf = FindFirstFile((LPCWSTR)&drctr.str, &FindFileData);
    if (hf == INVALID_HANDLE_VALUE)
    {
        printf("Error opening files or no files found!");
        return 1;
    }
    else
    {
        do
        {
            printf("Found file: %ls", FindFileData.cFileName);
            printf("\n");
        } while (FindNextFile(hf, &FindFileData) != 0);
        FindClose(hf);
    }

    free(drctr.str); 

标签: c++winapi

解决方案


您正在编译您的程序UNICODE启用。您正在调用 Win32 API 函数的 TCHAR 版本,这些函数映射到 Unicode 版本,这就是函数需要LPCWSTR( const wchar_t*) 字符串的原因。

如果您需要使用char字符串,请改用 ANSI 版本的 Win32 API 函数,例如;

struct drtctrAr
{
    char* str = NULL;
}; 

int main()
{
    system("chcp 1251");

    char tmpstr[1000];
    drtctrAr drctr;
    int len;
    
    printf("Please enter the directory: ");
    gets_s(tmpstr, 1000);

    len = strlen(tmpstr)+1;
    drctr.str = (char*)malloc(sizeof(char) * len);
    strcpy_s(drctr.str, len, tmpstr);

    WIN32_FIND_DATAA FindFileData;
    HANDLE hf;

    hf = FindFirstFileA(drctr.str, &FindFileData);
    if (hf == INVALID_HANDLE_VALUE)
    {
        printf("Error opening files or no files found!");
        free(drctr.str); 
        return 1;
    }
    else
    {
        do
        {
            printf("Found file: %s\n", FindFileData.cFileName);
        } while (FindNextFileA(hf, &FindFileData));
        FindClose(hf);
    }

    free(drctr.str); 

否则,将代码更改为使用wchar_t字符串:

struct drtctrAr
{
    wchar_t* str = NULL;
}; 

int main()
{
    system("chcp 1251");

    wchar_t tmpstr[1000];
    drtctrAr drctr;
    int len;
    
    printf("Please enter the directory: ");
    _getws_s(tmpstr, 1000);

    len = lstrlenW(tmpstr)+1;
    drctr.str = (wchar_t*)malloc(sizeof(wchar_t) * len);
    wcscpy_s(drctr.str, len, tmpstr);

    WIN32_FIND_DATA FindFileData;
    HANDLE hf;

    hf = FindFirstFileW(drctr.str, &FindFileData);
    if (hf == INVALID_HANDLE_VALUE)
    {
        printf("Error opening files or no files found!");
        free(drctr.str);
        return 1;
    }
    else
    {
        do
        {
            wprintf(L"Found file: %s\n", FindFileData.cFileName);
        } while (FindNextFileW(hf, &FindFileData));
        FindClose(hf);
    }

    free(drctr.str); 


推荐阅读