【问题标题】:C using a string in shell commandC在shell命令中使用字符串
【发布时间】:2013-05-01 22:44:01
【问题描述】:

您好,我正在尝试执行此 shell 命令“rm -rf test”:

#include <stdio.h>
#include <stdlib.h>


char name[] = "test";
char buffer[64];
int main()
{
        snprintf(buffer,sizeof(buffer),"rm -rf s% s%", name);
        system(buffer);
        return 0;
}

它将编译并运行,但不会删除目录

任何帮助将不胜感激!

【问题讨论】:

  • 你重复了 %s 两次 - 应该只是 "rm -rf %s"
  • s% 到底是什么?我相信你的意思是%s
  • 格式修饰符的形式是%s,而不是s%。
  • 使用 "rm -rf %s" 它仍然没有删除测试目录!不过谢谢你在这点上纠正我,肯定还有其他问题!
  • 非常糟糕的主意,stormCloud 的修复也无济于事。考虑当字符串名称为 "test /" 时会发生什么。

标签: c linux unix


【解决方案1】:

不要使用system 运行外部进程,尤其是当您传递的命令行不是恒定的时。它只会让你的生活变得悲惨。请参阅 man forkman exec 了解正确的方法。

【讨论】:

    【解决方案2】:
    #include <stdio.h>
    #include <stdlib.h>
    
    char name[] = "test";
    char buffer[64];
    
    int main()
    {
            snprintf(buffer,sizeof(buffer),"rm -rf %s", name);
            system(buffer);
            return 0;
    }
    

    它对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多