我需要将下面的例句保存为名为 demo.sh
的文件。
#!/usr/bin/env bash
xmessage This is "first sentence"
xmessage This is 'second sentence'
xmessage This is {third sentence}
我在 C 中使用的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
system("sudo bash -c 'printf \"#!/usr/bin/env bash\n\" > /usr/share/applications/demo.sh'");
return 0;
}
我可以将上面4句中的第一句OK写入文件中。但其他句子包含特殊字符,例如单引号
、双引号
和行结束符
。这变得非常难以逃脱,因为 sudo
命令需要有两个嵌套部分,我试图分别用 '
和 "
包裹它们。
如何转义句子并将其写入文件?如果能有一些功能就太好了,因为实际上该文件超过 4 个句子,并且有很多特殊字符。
请注意,我知道我可以使用 C 的 I/O 函数,我想通过使用 sudo
、 的单个
和system
命令来写入文件>printf单行字符串
。
最佳答案
我不认为这是最好的方法,但您可以使用一个 char[] 变量作为系统命令,并使用 sprintf() 函数在该变量中拆分和写入命令
这是一个例子
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char command[128];
/* Generate string */
sprintf(command, "sudo bash -c %s %s bash\n > /usr/share/applications/demo.sh'",
"'printf", "#!/usr/bin/env");
system(command);
return 0;
}
关于c - 如何正确转义嵌套特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29435381/