我有以下路径和文件名
"C:\\Users\\msi\\Desktop\\read-file\\read-file.sdf"对于PathFindExtensionW函数,预期的返回字符串是".sdf",但它返回"."!
这是我的code:
#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,但它返回了相同的结果。
发布于 2018-07-21 00:14:29
您的程序是Unicode (这是推荐的),您实际上不需要TEXT宏,它只在定义UNICODE时添加L前缀。你可以自己做:
const wchar_t *wstr = L"this is a wide char string"; //or const WCHAR*, same thingPathFindExtension是一个宏,在定义UNICODE时它被定义为PathFindExtensionW。
#ifdef UNICODE
#define PathFindExtension PathFindExtensionW
#else
#define PathFindExtension PathFindExtensionA
#endif // !UNICODE所以你可以直接写PathFindExtension
lstrcpy副本很好,但它是一个特定于Windows的函数。新程序可以使用宽字符版本的字符串函数,wcscpy代替strcpy,wcslen代替strlen,wcsxxx代替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;
}发布于 2018-07-20 15:15:30
当我们打算使用printf打印一个wide-string时,我们应该使用"%ls"格式说明符,而不是"%s"。
但是,将"%s"与wprintf结合使用是非常好的。
这是一条规则:
WCHAR *wstr = "this is wide string";
CHAR *str = "this is string";
wprintf("%s", wstr);
printf("%ls", wstr);
printf("%s", str);https://stackoverflow.com/questions/51445421
复制相似问题