c++ - 如何将 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);
解决方案
您正在编译您的程序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);
推荐阅读
- reactjs - 如何禁用 Material 的暗模式 - UI
- java - 错误:插入新数据@ManyToMany 时“表中不存在键”
- reactjs - 重新渲染子组件并在父状态更改时更改子状态状态
- python - 数量增加百分比第 2 部分
- reactjs - 在同一端口 80 上运行用于后端服务器代码的 Docker 容器和用于 React 前端代码的 Nginx
- powershell - 我需要在 Powershell 中获取我的 smb 共享的网络路径并将其输出到文本文档
- c# - 打开的 Oracle 连接过多
- python - Python 脚本使用的内存超出了应有的范围
- javascript - 在 javascript 中更改 Textarea 的值
- python - XlsxWriter 未向空单元格添加底部边框