我試圖使用sudo dd if=/dev/sda ibs=1 count=64 skip=446
命令從主引導記錄獲取分區表信息以解析它我基本上試圖讀取輸出到一個字符串,以解析它,但我得到的是以下內容:� !
。我很期待是:無法在C++程序中獲取Linux'dd'命令的輸出
80 01 01 00 83 FE 3F 01 3F 00 00 00 43 7D 00 00 00 00 01 02 83 FE 3F 0D 82 7D 00 00 0C F1 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
我當前的代碼看起來是這樣的,而且是剛剛從這裏取:How to execute a command and get output of command within C++ using POSIX?
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
using namespace std;
string exec(const char* cmd) {
char buffer[128];
string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe) throw std::runtime_error("popen() failed!");
try {
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
int main() {
string s = exec("sudo dd if=/dev/sda ibs=1 count=64 skip=446");
cout << s;
}
很顯然,我做錯了什麼,但我可以」找出問題所在。我如何獲得正確的輸出到我的字符串?
順便說一句,你應該閱讀[爲什麼是「while(!feof(file))」總是錯的?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file -always-wrong) – molbdnilo
如果從命令行運行該命令,那麼輸出結果會是你期望的嗎?我非常懷疑它,因爲命令只會轉儲原始二進制數據。原始的二進制數據不能像文本一樣處理。 –
另外,你爲什麼要把讀取循環放在'try-catch'中?唯一可能導致異常的情況是,如果在附加到字符串的同時內存不足。即使如此,程序終止也會關閉管道,所以沒有實際需要。 –