c - 从 c 中的 system() 调用时找不到 gcc

标签 c file gcc system sh

到目前为止,我已经尝试了 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,而不是完整路径。

谢谢!

最佳答案

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';

关于c - 从 c 中的 system() 调用时找不到 gcc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23417776/

相关文章:

linux - '-rwxrwxrwx'中的连字符是什么意思

java - 如何检查文件是否为二进制文件?

java - 创建相关 java.io.File 的安全方法

c++ - 交叉编译找不到动态链接库

c - 为什么 (unsigned int) 在 C 的输出中产生负数

MySQL临时表查询-将计算列添加到select中计算的表中

c - 末尾不带数字的两位数字符串加法

c - MAX 使用 gcc 的 typeof 扩展

c - 通过 gcc 进行 c 编译时出现 undefined reference 错误

gcc - 位置无关的可执行文件和固定入口点地址