gpt4 book ai didi

c - PathFindExtensionW 始终返回 "."而不是完整扩展名

转载 作者:太空宇宙 更新时间:2023-11-04 02:25:47 25 4
gpt4 key购买 nike

我有以下路径和文件名

"C:\\Users\\msi\\Desktop\\read-file\\read-file.sdf"

使用 PathFindExtensionW 函数,预期的返回字符串是 ".sdf" 但它返回 "." 而不是!

这是我的代码:

#include <stdio.h>
#include <shlwapi.h>

#define FILENAME "C:\\Users\\msi\\Desktop\\read-file\\read-file.sdf" // current file-path
#define MAX_FILE_EXT 90 // maximum file-extension length
#define ERR_MSG "Cannot open the specific file!\n" // error message if couldn't open the file

#pragma comment(lib, "shlwapi.lib") // add this static library for using of PathFindExtension

int main(int argc, char *argv[])
{
WIN32_FIND_DATAW data = {0};
HANDLE fh = 0;

if((FindFirstFile(TEXT(FILENAME), &data)) != INVALID_HANDLE_VALUE)
{
WCHAR file_ext[MAX_FILE_EXT] = {0};
lstrcpy(file_ext, PathFindExtension(TEXT(FILENAME)));

printf("File-extension is : '%s'\n", PathFindExtensionW(TEXT(FILENAME)));
}
else
printf(ERR_MSG);

return 0;
}

顺便说一下,我使用了wchar_t*,所以我不得不调用PathFindExtensionW。虽然我调用了 PathFindExtension,但它返回了相同的结果。

最佳答案

您的程序是 Unicode(推荐),您并不需要 TEXT 宏,它只在 UNICODE 时添加 L 前缀被定义为。你可以自己做:

const wchar_t *wstr = L"this is a wide char string"; //or const WCHAR*, same thing

PathFindExtension是一个宏,定义UNICODE时,定义为PathFindExtensionW

#ifdef UNICODE
#define PathFindExtension PathFindExtensionW
#else
#define PathFindExtension PathFindExtensionA
#endif // !UNICODE

所以你可以只写PathFindExtension

lstrcpy 复制没问题,但它是 Windows 特定的功能。新程序可以使用宽字符版本的字符串函数,wcscpy 代替 strcpywcslen 代替 strlenwcsxxx 而不是 strxxx ...

"C:\\Users\\msi\\Desktop" 不应进行硬编码。使用SHGetKnownFolderPath 查找桌面路径,示例:

#include <windows.h>
#include <stdio.h>
#include <shlwapi.h>
#include <Shlobj.h>
#include <KnownFolders.h>

#pragma comment(lib, "shlwapi.lib")

int main(void)
{
wchar_t desktop[MAX_PATH];

//get desktop path:
wchar_t *ptr;
SHGetKnownFolderPath(&FOLDERID_Desktop, 0, NULL, &ptr);
wcscpy_s(desktop, _countof(desktop), ptr);
CoTaskMemFree(ptr);

//make filename from desktop path:
wchar_t filename[MAX_PATH];
swprintf(filename, _countof(filename), L"%s\\read-file\\read-file.sdf", desktop);

if (PathFileExists(filename))
wprintf(L"File-extension is : '%s'\n", PathFindExtension(filename));

return 0;
}

关于c - PathFindExtensionW 始终返回 "."而不是完整扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51445421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com