【发布时间】:2017-04-04 09:53:37
【问题描述】:
我正在尝试使用sudo dd if=/dev/sda ibs=1 count=64 skip=446 命令从主引导记录中获取分区表信息以对其进行解析我基本上是在尝试将输出读取为字符串以进行解析,但是所有我得到的是以下内容:� !。我期待的是:
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;
}
显然我做错了什么,但我无法找出问题所在。如何将正确的输出输入到我的字符串中?
【问题讨论】:
-
如果你从命令行运行命令,输出会是你所期望的吗?我严重怀疑它,因为该命令只会转储原始二进制数据。并且无法像文本一样处理原始二进制数据。
-
另外,你为什么将阅读循环放在
try-catch中?唯一可能导致异常的是,如果您在附加到字符串时内存不足。即便如此,程序终止还是会关闭管道,因此实际上没有必要。 -
啊,谢谢。我添加了
| hexdump -C,现在可以正常使用了 -
你为什么还要在外部进程中运行
dd?你可以随便open("/dev/sda"...)和seek(446)和read(64...)。