gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:55:47 25 4
gpt4 key购买 nike

我正在尝试让我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com