【问题标题】:gcc not found when calling from system() in c从 c 中的 system() 调用时找不到 gcc
【发布时间】:2014-05-01 22:31:19
【问题描述】:

到目前为止,我已经尝试了 2 种方案,其中只有一种有效,但有效的不是我想要使用的。

在我的 c 程序中,我可以进行以下调用:

system("gcc filename.c");

这很好用,但这意味着我必须对文件名进行硬编码......但我想做的是让用户输入文件名,然后从给定的输入编译它。这就是我所拥有的:

    char fileName[50];

    puts("Please enter the path to the file and name [including the .c extension (Example: /root/CS250/labs/lab9.c)]:");
    printf("\t? "); //Formating purposes
    scanf("%s", fileName); //Read in the file name [contains no spaces]

    printf("Compling file: %s with gcc command: ", fileName);

    //Building the command
    char command[75]; //random length of 75
    strcat(command, "gcc ");
    strcat(command, fileName);
    printf("%s\n", command);
    printf("Return from system call: %d\n", system(command));

当我运行这段代码时,这是我输入的内容和我从输出中得到的内容:

? 2
Please enter the path to the file and name [including the .c extension (Example: /root/CS250/labs/lab9.c)]:
    ? ~/CS2/labs/lab8.c #COMMENT: This is the correct path to the file
    Compling file: ~/CS2/labs/lab8.c with gcc command: gcc ~/CS2/labs/lab8.c
    **sh: 1: gcc: not found //The error**
    Return from system call: 32512 //Exit code...

这里有什么问题?我不能用包含命令的 char[] 调用系统吗?我该如何解决这个问题? [文件路径正确,gcc 工作正常,我可以运行 system("gcc blah.c");它会正确编译;我也试过打电话:/usr/bin/gcc。

另一个注意事项:如果有人能告诉我如何绕过输入文件的完整路径,那就太好了!我是什么意思?现在你必须输入/root/folder/x.txt,但程序存储在/root/folder/,所以我只想输入x.txt,而不是完整路径。

谢谢!

【问题讨论】:

  • 为我工作。当您调用系统的默认 shell 时,请确保 gcc 在您的 PATH 中(system 就是这样做的)。
  • 如果您使用strcpy(command, "gcc "); 而不是strcat(command, "gcc ");,是否有效? command数组第一次访问时可能有随机数据;不能保证一开始都是零。
  • @MarkPlotnick 谢谢,那行得通!它没有正确地“清零”字符串。
  • @user2494817 局部变量默认不归零,要写= { 0 };

标签: c file gcc system sh


【解决方案1】:
char command[75]; //random length of 75
strcat(command, "gcc ");

是一个非常个坏主意,因为您实际上并不知道在您附加“gcc”时command 中的内容。它可能有一个单字符的不可打印控制字符,看起来仍然有效,但不会作为可执行文件找到。

检查这一点的一种方法是在strcat 之后执行printf("%x\n",*command) 以检查第一个字符是否实际上 g (0x67)。但是,无论如何,您所做的事情都是不安全的——第一个 strcat 几乎肯定应该是 strcpy,所以您有一个已知的起点(a)


(a) 如果你真的一心想要在任何地方使用strcat(但我看不出你需要这样做的真正原因) ,您至少应该在开始之前将缓冲区设为空字符串:

*command = '\0';

【讨论】:

    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 2011-08-23
    相关资源
    最近更新 更多