c++ - 将 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());
解决方案
您不能分配给数组。您应该使用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 版本 ( char
and GetModuleFileNameA
) 更安全,std::string
其他需要字符串的 API 包括char
.
推荐阅读
- java - 如何使用 1 个 Spring Batch 作业来处理多个请求
- javascript - window.print() 不仅提供选定的选项
- angular - 如何在使用 Angular 8 上传到服务器端之前加密图像?
- javascript - 如何通过 document.getElementById inAngular 更改显示
- pandas - 在多个条件下过滤数据帧索引
- javascript - Vue组件中的子值更改父值的问题
- angular - Jasmine:当测试返回 SPEC HAS NOT EXPECTATION 时?
- c# - ILogger 未注入 Durable Functions v2.0
- rundeck - Rundeck AD 身份验证问题,它给出了无效的用户名和密码
- java - for 循环的值未按正确顺序打印