Peter
Peter

Reputation: 345

TCHAR Array to a concatenate LPCSTR

I am reading a ini file and want to execute a external program (VBS File) after that. But I am having problems with the string types.

This is my code.

LPCTSTR path = _T(".\\my.ini");
TCHAR fileName[500];
int b = GetPrivateProfileString(_T("Paths"), _T("filename"), _T(""), fileName, 500, path);
// fileName = myscript.vbs
// I need to execute "wscript myscript.vbs arg1"
// Execute script file. Doesnt work.
WinExec("wscript " + fileName + " arg1", MINIMZIED);
// OR. Doesnt work.
system("wscript " + fileName + " arg1");

This doesnt work. WinExec wants a LPCSTR but I have the fileName in a TCHAR[] and want to concatenate with some other string.

How can I convert or concatenate it correctly?

Upvotes: 0

Views: 965

Answers (2)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32717

From the WinExec() documentation:

This function is provided only for compatibility with 16-bit Windows. Applications should use the CreateProcess function.

Which is CreateProcessW() in your case.

Alternatively, you can use _wsystem().

Upvotes: 2

Remy Lebeau
Remy Lebeau

Reputation: 597016

You need to concatenate the strings using another buffer, for example:

LPCTSTR path = _T(".\\my.ini");
TCHAR fileName[500];
TCHAR command[520];

int b = GetPrivateProfileString(_T("Paths"), _T("filename"), _T(""), fileName, 500, path);
_stprintf_s(command, 520, _T("wscript %.*s arg1"), b, filename);

Then you can use command as needed, eg:

STARTUPINFO si = {};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_MINIMIZED;

PROCESS_INFORMATION pi = {};

if (CreateProcess(NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
{
    ...
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
}

Or:

#ifdef UNICODE
#define system_t(cmd) _wsystem(cmd)
#else
#define system_t(cmd) system(cmd)
#endif

system_t(command);

Upvotes: 1

Related Questions