gpt4 book ai didi

c - 将 Unix 命令的输出存储在 C 代码中

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:40 24 4
gpt4 key购买 nike

int main()  {
char buf[100];
FILE *fp = popen("df -P /myLoc", "r");
while (fgets(buf, 100, fp) != NULL) {
printf( "%s", buf);
}
pclose(fp);

return 0;
}

输出:

Filesystem             512-blocks  Used  Available Capacity Mounted on
/dev0/vol0 123456 3456 5464675 4% /sys

我在 buf 变量中得到命令的输出。但我需要将 Capacity 的值(在本例中为 4)放入一个整型变量中。我认为可以使用 cut 或 awk 命令,但不确定如何使其正常工作。

感谢任何帮助。

最佳答案

如果你想使用 shell 工具,你应该写一个 shell 脚本。

如果这真的必须在 C 中,您应该使用 POSIX 提供的系统调用,而不是通过 popen 将事情拼凑在一起。在你的情况下,这将是 statvfsstatvfs 结构的成员 f_favail

#include <stdio.h>
#include <sys/types.h>
#include <sys/statvfs.h>

int main()
{
struct statvfs buf;
statvfs("/my/path", &buf);
printf("Free: %lu", buf.f_favail);

return 0;
}

关于c - 将 Unix 命令的输出存储在 C 代码中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16786053/

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