c - 如何从 C 程序构建用于 Unix system() 调用的字符串

标签 c unix command

我正在尝试让我的 C 程序使用 system() 在 Unix 中运行命令。

我可以制作类似 system("stat myFile") 的东西,其中 myFile 是我程序中的变量吗? 还有其他办法吗?

最佳答案

system() 接受一个指向 char 的指针或一个 char 数组。您可以按如下方式构建它:

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

char command[256]; /* Big enough for "stat " + longest file name. */
char *myFile = "/my/file";
/* ... */
sprintf (command, "stat %s", myFile);
system(commmand);

这应该能让你继续下去,但请注意,像 256 这样的硬限制并不是防弹编码,因为如果 myFile 是一个很长的名称,可能会导致缓冲区溢出。 Supercalifragilisticexpialidocious 文件名并非闻所未闻:-) 如果您想像专业人士一样操作,下一步就是阅读 snprintf 手册并向您的 shell 询问 getconf _POSIX_PATH_MAX

关于c - 如何从 C 程序构建用于 Unix system() 调用的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26494644/

相关文章:

c - strlen AVX-512 __builtin_ctz 无效值

c - 使用 cURL 的段错误

bash - 将文件内容附加为 unix shell 命令的参数

linux - 使用后台进程优化脚本以提高速度

docker - docker ps -a是什么意思

c++ - 更改组合框选择的 DateTimePicker 样式失败

bash - 问 : Permission denied when I source . bash_profile

linux - jmeter执行复杂的shell命令

wpf - MVVM 中的命令

c - 在C中实现Realloc