【发布时间】:2017-11-18 10:50:17
【问题描述】:
我创建了一个名为“myscript.h”的简单 bash 脚本,我给它一个 .h 扩展名,原因我不会在这里透露。此 bash 脚本位于“/var/ftp/something with spaces”中。
在终端中,我可以输入“/var/ftp/something with spaces/myscript.h”,脚本运行良好。
但是,在我的 C 程序中,我输入了
system("/var/ftp/something with spaces/myscript.h")
它抱怨找不到“/var/ftp/something”。我已使用正斜杠将系统调用更改为以下内容:
system("/var/ftp/something\ with\ spaces/myscript.h")
但是,它仍然抱怨找不到“/var/ftp/something”。假设我无法更改目录名称,我该如何解决这个问题?
谢谢!
【问题讨论】:
-
尝试使用转义序列 \" 在字符串中添加引号:system("\"/var/ftp/something with spaces/myscript.h\"");
-
使用
.h扩展名调用 bash 脚本很有趣... -
您可以使用
execl("/var/ftp/something with spaces/myscript.h", NULL)(首先使用fork)高效而稳健地运行您的程序。system()是为了“方便”,速度较慢,更脆弱,可能有安全隐患。 -
简短回答:反斜杠由 c-lexer 解释:
'\ '等于空格。因此,您应该将它们加倍,shell 将看到一个反斜杠加上一个空格。 (或者:使用'\"或'\''将整个内容放入转义引号中,就像在其中一个答案中一样) -
@Izzo:因为 C 在双引号字符串中解析反斜杠,所以实际上需要将每个反斜杠写为 \\。因此,反斜杠转义的命令是
system("/var/ftp/something\\ with\\ spaces/myscript.h")。在 POSIXy 系统中,您可以使用单引号,即。system("'/var/ftp/something with spaces/myscript.h'").