![](/img/trans.png)
[英]How to store an output from a UNIX command into a char with in C programming
[英]Store output from Unix command in C code
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
內容拼湊在一起。 在您的情況下,這將是statvfs
和statvfs
結構的成員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;
}
將df
命令替換為df -P /myLoc | awk '{print $5}' | tail -n 1 | cut -d'%' -f 1
df -P /myLoc | awk '{print $5}' | tail -n 1 | cut -d'%' -f 1
df -P /myLoc | awk '{print $5}' | tail -n 1 | cut -d'%' -f 1
。
在您的情況下,這將返回4。 然后,您可以使用atoi()
將其轉換為int。
但是,正如其他人所建議的那樣,使用系統調用至少應該更具可移植性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.