c++中如何用char数组提供_tcsdup函数

How to provide _tcsdup function with char array in c++?

本文关键字:tcsdup 函数 数组 何用 char c++      更新时间:2023-10-16
LPTSTR szCmdline = _tcsdup(TEXT("C:\Users\incemehm\Desktop\EncryptZipFtp.exe"));

这个符号可以工作,但我想手动创建命令行。像下图:

char *fProg = "C:\Users\incemehm\Desktop\EncryptZipFtp.exe";
char *fPath = "C:\Users\incemehm\Desktop\Foto";
char *fPass = "wxRMKH1994wxRMK";
char command[500];
sprintf (command, "%s %s %s", fProg, fPath, fPass); 

和用法:

LPTSTR szCmdline = _tcsdup(TEXT(command));

但是它给出了错误error C2065: 'Lcommand' : undeclared identifier

有什么问题吗?任何帮助吗?

您显示的代码

  • C代码,不是c++。

  • 适用于Windows 9x,不适用于现代Windows

  • const -不正确启动。

在现代Windows中使用宽字符串。替换

char *fProg = "C:\Users\incemehm\Desktop\EncryptZipFtp.exe";
char *fPath = "C:\Users\incemehm\Desktop\Foto";
char *fPass = "wxRMKH1994wxRMK";
char command[500];
sprintf (command, "%s %s %s", fProg, fPath, fPass); 

wstring const fProg  = L"C:\Users\incemehm\Desktop\EncryptZipFtp.exe";
wstring  const fPath = L"C:\Users\incemehm\Desktop\Foto";
wstring const fPass  = L"wxRMKH1994wxRMK";
wstring command = fProg + L' ' + fPath + L' ' + fPass;

其中wstringstd::wstring,来自<string>报头。

传递给API函数的地方,使用command.c_str()


附录:由于OP在注释中声明意图将此字符串传递给CreateProcess,请注意CreateProcess需要一个可变缓冲区。因此,你不能只是通过command.c_str()。相反,将其复制到另一个非constwstring(最简单的方法是使用command作为初始化表达式),假设它称为s,添加终止L'',并传递&s[0], & help;

wstring s = command + L'';
someFunc( &s[0] );

如果您正在使用TCHAR,则始终使用它。如:

TCHAR command[500];
_stprintf_s(command, _T("%s %s %s"), fProg, fPath, fPass);

您还可以将STL字符串定义为typedef std::basic_string<TCHAR> tstring;,以使用适当类型的c++字符串。但是您真的要在没有定义UNICODE的情况下进行编译吗?