df
次のコードを使用して、Linux でコマンドの結果を読み取ろうとしていますpopen
。
#include <iostream> // 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
否定的になりつつありますが、今ではその理由がわかりました. 私が素朴に試みたように、パイプにランダムにアクセスすることはできません。
私はこれをやろうとする最初の人になることはできません. system() 呼び出しの結果を C++ の変数に読み込む方法の例を教えて (または指摘して) もらえますか?