C系统无法运行hello world

puk*_*puk 1 c shell process

任何人都可以告诉我为什么这个systemshell hello world命令的简单C 调用不起作用:

MWE:

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

main( int argc, char *argv[] )
{
   char *str;

   str = strdup ( "hello" );
   printf ( "echo %s\n", str );
   system ( ( "echo %s\n", str ) );

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

回声你好

sh:1:你好:没找到

Tho*_*mas 6

这不符合你的想法:

   system ( ( "echo %s\n", str ) );
Run Code Online (Sandbox Code Playgroud)

逗号操作简单地返回所述第二值,str,这是"hello".因此,您的程序不会尝试运行echo hello,只是hello.

您将要使用sprintf将整个命令写入缓冲区,然后执行该操作.