首页 > 解决方案 > 将 char* 加入文件系统::path.filename() 或 char[260] 时出现问题

问题描述

我知道以前有人问过类似的问题,但对我来说没有一个问题有帮助。

基本上我想要dstPath= %AppData% + "CURRENT EXE NAME"

但问题在于不同的字符串类型和字符串连接

简化代码:-

#include <stdio.h>
#include <string>
#include <filesystem>

#include <Shlwapi.h>
#include <Windows.h>

using namespace std;

int main()
{
    TCHAR selfPath[MAX_PATH];
    TCHAR dstPath[MAX_PATH];
    
    if (GetModuleFileName(NULL, selfPath, MAX_PATH) == 0)       // Getting exe File Location
        printf("Error : %ul\n", GetLastError());
    
    filesystem::path p(selfPath);
    
    dstPath = strcat(getenv("APPDATA"), p.filename().string().c_str());     // Here Comes The Error
    
    printf("Src : %s\n", selfPath);
    printf("Dst : %s\n", dstPath);
    
    return 0;
}

编译器命令:-

g++ -Os -s -o ./builds/gcc-rat-x64.exe ./source/rat.cpp -std=c++17 -m64 -lshlwapi

编译器错误:-

error: incompatible types in assignment of 'char*' to 'TCHAR [260]' {aka 'char [260]'}
   80 |  dstPath = strcat(getenv("APPDATA"), p.filename().string().c_str());

标签: c++

解决方案


您不能分配给数组。您应该使用strcpy()来复制 C 风格的字符串。

strcpy(dstPath, getenv("APPDATA"));
strcat(dstPath, p.filename().string().c_str());

或者可以通过以下方式在一行中完成连接snprintf()

snprintf(dstPath, sizeof(dstPath), "%s%s", getenv("APPDATA"), p.filename().string().c_str());

最后,TCHAR可以GetModuleFileName参考UNICODE版本的API,根据编译选项。显式使用 ANSI 版本 ( charand GetModuleFileNameA) 更安全,std::string其他需要字符串的 API 包括char.


推荐阅读