我正在使用以下代码尝试使用popen在Linux中读取df命令的结果.
#include // file and std I/O functions
int main(int argc, char** argv) {
FILE* fp;
char * buffer;
long bufSize;
size_t ret_code;
fp = popen("df", "r");
if(fp == NULL) { // head off errors reading the results
std::cerr << "Could not execute command: df" << std::endl;
exit(1);
}
// get the size of the results
fseek(fp, 0, SEEK_END);
bufSize = ftell(fp);
rewind(fp);
// allocate the memory to contain the results
buffer = (char*)malloc( sizeof(char) * bufSize );
if(buffer == NULL) {
std::cerr << "Memory error." << std::endl;
exit(2);
}
// read the results into the buffer
ret_code = fread(buffer, 1, sizeof(buffer), fp);
if(ret_code != bufSize) {
std::cerr << "Error reading output." << std::endl;
exit(3);
}
// print the results
std::cout << buffer << std::endl;
// clean up
pclose(fp);
free(buffer);
return (EXIT_SUCCESS);
}
这段代码给我一个“内存错误”,退出状态为“2”,所以我可以看到它失败的地方,我只是不明白为什么.
我把它放在Ubuntu Forums和C++ Reference上找到的示例代码中,所以我没有和它结婚.如果有人可以建议更好的方式来阅读system()调用的结果,我会接受新的想法.
编辑到原文:好的,bufSize即将消极,现在我理解为什么.您不能随意访问管道,因为我天真地试图这样做.
我不能成为第一个尝试这样做的人.有人可以给(或指向我)一个如何将系统()调用结果读入C中的变量的示例吗?