【发布时间】: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 };