如何将外部管道的结果放入变量中?

问题描述 投票:0回答:1

这是我的代码(正在进行中,用于计算系统中磁盘的大小(以 GB 为单位))

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

int main ()
{
char line[128];
 FILE* file = popen("/usr/sbin/prtvtoc /dev/rdsk/c0b0t2d0s0 |/usr/local/bin/grep 'slice 0' -A 2|grep length|cut -d : -f 3|cut -d '(' -f 1|cut -c 2-1000", "w");
  printf("The size in 512b blocks of the disk /dev/rdsk/c0b0t2d0s0del is %s \n",file);
  pclose(file);
  return 0;
  }

输出很差

The size in 512b blocks of the disk /dev/rdsk/c0b0t2d0s0del is
41929587 

我想要

The size in 512b blocks of the disk /dev/rdsk/c0b0t2d0s0del is 41929587

我的想法是将 popen 管道的输出存储在变量中,但我不知道该怎么做:可能吗?

编辑1:

我试过这条线

  printf("The size in 512b blocks of the disk /dev/rdsk/c0b0t2d0s0del is %d \n",*file);

但返回0

c popen
1个回答
0
投票

您的代码中似乎存在一些问题。首先,当使用popen执行命令并读取其输出时,需要使用fgets或类似函数将输出读入缓冲区。其次,popen 的输出是 FILE*,而不是字符串,因此您需要使用适当的函数来读取它。

这是代码的更新版本:

c 复制代码 #包括 #包括

int main() { FILE *file = popen("/usr/sbin/prtvtoc /dev/rdsk/c0b0t2d0s0 | /usr/local/bin/grep '切片 0' -A 2 | grep 长度 | cut -d : -f 3 | cut -d '(' -f 1 | cut -c 2-1000", "r");

if (file == NULL) {
    perror("popen");
    return 1;
}

char line[128];
// Read the output into the 'line' buffer
if (fgets(line, sizeof(line), file) == NULL) {
    perror("fgets");
    return 1;
}

// Close the file stream
pclose(file);

// Remove trailing newline character, if any
size_t len = strlen(line);
if (len > 0 && line[len - 1] == '\n') {
    line[len - 1] = '\0';
}

// Print the result
printf("The size in 512b blocks of the disk /dev/rdsk/c0b0t2d0s0del is %s\n", line);

return 0;

} 此代码使用 fgets 将命令的输出读入行缓冲区。它还从字符串中删除尾随换行符(如果存在)。请注意,缓冲区(行)的大小应足以容纳命令的输出。

记得检查 popen、fgets 等函数的返回值是否有错误,以确保稳健的错误处理。

© www.soinside.com 2019 - 2024. All rights reserved.