如何获取C / C ++中的磁盘驱动器序列号

这已经被回答了,但是它是一个C#解决scheme。 如何在C或C ++中执行此操作?

有几种方法可以做到这一点。 您可以使用系统拨打电话来获取信息。

对于Linux:

system("hdparm -i /dev/hda | grep -i serial"); 

不使用系统:

 static struct hd_driveid hd; int fd; if ((fd = open("/dev/hda", O_RDONLY | O_NONBLOCK)) < 0) { printf("ERROR opening /dev/hda\n"); exit(1); } if (!ioctl(fd, HDIO_GET_IDENTITY, &hd)) { printf("%.20s\n", hd.serial_no); } else if (errno == -ENOMSG) { printf("No serial number available\n"); } else { perror("ERROR: HDIO_GET_IDENTITY"); exit(1); } 

对于Windows:

 system("wmic path win32_physicalmedia get SerialNumber"); 

不使用系统(基于获取WMI数据 ):

 hres = pSvc->ExecQuery( bstr_t("WQL"), bstr_t("SELECT SerialNumber FROM Win32_PhysicalMedia"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator); hr = pclsObj->Get(L"SerialNumber", 0, &vtProp, 0, 0); 

Linux:请参阅/ sys / class / ata_device / dev * / id

在我的系统上有四个用户可读的文件,包含设备信息的十六进制转储; 其中两个全是零,另外两个包含有关磁盘和DVD的信息; DVD没有序列号,磁盘序列号从偏移量0x20开始。

对于Windows: wmic path win32_physicalmedia get SerialNumber

以下是如何取回数据作为运行任何命令的字符串 。 我们正在使用_popen而不是上面提到的system

 #include <cstdio> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <array> exec("wmic path win32_physicalmedia get SerialNumber"); std::string exec(const char* cmd) { std::array<char, 128> buffer; std::string result; std::shared_ptr<FILE> pipe(_popen(cmd, "r"), _pclose); if (!pipe) throw std::runtime_error("_popen() failed!"); while (!feof(pipe.get())) { if (fgets(buffer.data(), 128, pipe.get()) != NULL) result += buffer.data(); } return result; }