我如何使用 `execl()` 在 C/C++ 中 运行 系统命令,仅将函数参数作为命令行而不是可执行文件传递?
How can I run system commands in C/C++ using `execl()`, passing the function arguments only as a command line, not as an executable file?
我想在 C/C++ 程序中执行此命令:stat -c "%F %A %n" *filename goes here*
文件名存储在 main
函数的 argv[1]
.
中
我试了一下 execl("/bin/stat", "stat", "-c", "\"%F %A %n\"", "file", NULL);
execl()
命令应该如何实现结果?
您的命令应如下所示:
int res = execl("/bin/stat", "stat", "-c", "\"%F %A %n\"", argv[1], NULL);
if (res == -1) {
perror("/bin/stat");
exit(1);
}
然后错误会显示:
/bin/stat: No such file or directory
你会意识到 stat 在 /usr/bin 中或者使用 execlp 是个好主意。
我发现了我的问题。 stat
命令位于 /usr/bin
而不是 /bin
.
我想在 C/C++ 程序中执行此命令:stat -c "%F %A %n" *filename goes here*
文件名存储在 main
函数的 argv[1]
.
我试了一下 execl("/bin/stat", "stat", "-c", "\"%F %A %n\"", "file", NULL);
execl()
命令应该如何实现结果?
您的命令应如下所示:
int res = execl("/bin/stat", "stat", "-c", "\"%F %A %n\"", argv[1], NULL);
if (res == -1) {
perror("/bin/stat");
exit(1);
}
然后错误会显示:
/bin/stat: No such file or directory
你会意识到 stat 在 /usr/bin 中或者使用 execlp 是个好主意。
我发现了我的问题。 stat
命令位于 /usr/bin
而不是 /bin
.