无法将PathFindExtensionW输出分配给WCHAR数组

时间:2018-08-20 07:12:10

标签: c winapi visual-studio-2012 console-application

我想将PathFindExtensionW api的输出分配给WCHAR数组。此api返回LPWSTR指针。我搜索并发现了将LPWSTR分配给WCHAR数组的方法,如下所示:

WCHAR array[100] = PathFindExtensionW(,,,)

但是它对我不起作用,并且我收到此错误:

表达式必须是可修改的左值

我正在使用VS2012。我的代码如下:

#include <windows.h>
#include <iostream>
#include "Shlwapi.h"

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

void main(int argc, char *argv[]){

    int iToSizeB = 0;
    iToSizeB = MultiByteToWideChar(CP_UTF8, 0, argv[1], -1 , NULL, 0);

    WCHAR lpFileAddress[260] = {0};
    MultiByteToWideChar(CP_UTF8, 0, argv[1], -1, lpFileAddress, iToSizeB);

    WCHAR lpDotPosition[260] = {0};

    //this line must be correct but I receive error
    lpDotPosition = PathFindExtensionW(lpFileAddress);

    int iToSizeW = 0;
    iToSizeW = WideCharToMultiByte(CP_UTF8, 0, lpDotPosition, -1, NULL, 0, NULL, NULL);

    CHAR lpExtension[260] = {0};
    WideCharToMultiByte(CP_UTF8, 0, lpDotPosition, -1, lpExtension, iToSizeW, NULL, NULL);

    printf("the format is:\n");
    printf(lpExtension);
    printf("\n");

    getchar();
}

这是怎么了?

感谢您的解决方案。

1 个答案:

答案 0 :(得分:0)

不能通过为数组分配指针来填充数组。您必须复制数据,例如使用lstrcpynW()或类似功能:

LPCWSTR lpDotPosition = PathFindExtensionW(lpFileAddress);

WCHAR lpExtensionW[MAX_PATH] = {0};
lstrncpy(lpExtensionW, lpDotPosition, MAX_PATH);

但是,PathFindExtension()只是在您传入的字符串缓冲区内返回一个指针,因此无需分配扩展名的单独副本,数据已预先分配,返回的指针将只要输入字符串有效,就保持有效:

#include <windows.h>
#include <iostream>
#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")

int main(int argc, char *argv[])
{
    WCHAR lpFileAddress[MAX_PATH] = {0};
    int iToSizeB = MultiByteToWideChar(CP_UTF8, 0, argv[1], -1, lpFileAddress, MAX_PATH);

    LPCWSTR lpDotPosition = PathFindExtensionW(lpFileAddress);

    CHAR lpExtension[MAX_PATH] = {0};
    int iToSizeW = WideCharToMultiByte(CP_UTF8, 0, lpDotPosition, -1, lpExtension, MAX_PATH, NULL, NULL);

    printf("the format is:\n%s\n", lpExtension);

    getchar();
    return 0;
}

另一方面,无需仅使用MultiByteToWideChar()WideCharToMultiByte()来搜索char字符串,而可以使用PathFindExtensionA()

#include <windows.h>
#include <iostream>
#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")

int main(int argc, char *argv[])
{
    LPCSTR lpExtension = PathFindExtensionA(argv[1]);

    printf("the format is:\n%s\n", lpExtension);

    getchar();
    return 0;
}