【发布时间】:2020-02-13 09:09:26
【问题描述】:
sh -c 'ls C:\Users\timothee'
给予:
ls: 无法访问 'C:Userstimothee': 没有这样的文件或目录
sh -c 'ls C:\\Users\\timothee'
给出: ls: 无法访问 'C:Userstimothee': 没有这样的文件或目录
这些作品:
sh -c 'ls C:\\\Users\\\timothee'
sh -c 'ls C:/Users/timothee'
但是没有更好的方法吗?
我正在尝试使用CreateProcess 以编程方式调用shell(bash 或sh)命令并正确转义它,但是反斜杠的奇怪吞咽使这很尴尬。请参见下面的 C 示例:
这是下面最好的方法吗,使用 6(!) 反斜杠?
(我的完整程序必须将输入例如echo C:\\Users\\timothee 转换为:
echo C:\\\\\\Users\\\\\\timothee)
#ifdef _WIN32
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <stdio.h>
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void _tmain2(TCHAR *argv)
{
// adapted from https://stackoverflow.com/questions/42531/how-do-i-call-createprocess-in-c-to-launch-a-windows-executable
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line)
argv, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
printf( "CreateProcess failed (%d).\n", GetLastError() );
return;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
int main (int argc, char *argv[]) {
//char s[] = "echo ok1 && echo ok2"; // bad (prints: ok1 && echo ok2)
//char s[] = "sh -c 'echo ok1 && echo ok2'"; // ok: prints ok1\nok2
//char s[] = "sh -c 'echo C:\\Users\\timothee\\'"; // error
//char s[] = "sh -c 'echo C:/Users/timothee'"; // ok but I want \, not / as some windows program don't understand /
//char s[] = "sh -c 'echo C:\\\\Users\\\\timothee'"; // BUG: prints: C:Userstimothee
char s[] = "sh -c 'echo C:\\\\\\Users\\\\\\timothee'"; // prints: C:\Users\timothee
_tmain2(s);
return 0;
}
#endif //win32
链接:
【问题讨论】:
标签: windows bash escaping sh backslash