c++获取硬盘or分区序列号

        在使用 Windows 时,可以使用命令获取硬盘分区的(或多或少唯一的)序列号。

GetVolumeInformation()

示例代码:

#include <iostream>

#include <windows.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    DWORD VolumeSerialNumber;
    char VolumeName[256];
    GetVolumeInformation("c:\\ ", VolumeName, 12, &VolumeSerialNumber, NULL, NULL, NULL, 10);
 
    printf("c盘的卷标:%s\n ", VolumeName);
    printf("c盘的序列号:%lu\n ", VolumeSerialNumber);

    return 0;
}

结果:

c盘的卷标:Windows 
c盘的序列号:3831598124

        Linux 有类似的东西吗?获得硬件设备的唯一编码,并且可以通过编程方式检索?

解决方案:

        在 linux 中,可以使用 blkid 命令获取分区的 UUID:

# sudo blkid /dev/sda1
/dev/sda1: UUID="007258df-98ea-47de-b906-35997ea63509" TYPE="ext4" PARTUUID="5c1bef5e-01"

        此信息以特定分区类型(如 ext4、xfs)的格式存储,并在重新格式化时发生变化。

        如果需要从代码中调用它,调用一个 shell 来运行这个命令并不是最好的方法,但它可以工作:

// main.cpp
#include <stdio.h>

int main(int argc,char ** argv) 
{
  /* device you are looking for */   
  char device[]="/dev/sda1";

  /* buffer to hold info */
  char buffer[1024];

  /* format into a single command to be run */
  sprintf(buffer,"/sbin/blkid -o value %s",device);

  /* run the command via popen */
  FILE *f=popen(buffer,"r");

  /* probably should check to make sure f!=null */
  /* read the first line of output */
  fgets(buffer,sizeof(buffer),f);

  /* print the results (note, newline is included in string) */
  fprintf(stdout,"uuid is %s",buffer);
}

CMakeLists.txt

# 声明要求的 cmake 最低版本
cmake_minimum_required(VERSION 2.8)

# 声明一个 cmake 工程
project(blkid_sd)

# 设置编译模式
set(CMAKE_BUILD_TYPE "RELEASE")

# 添加一个可执行程序
# 语法:add_executable( 程序名 源代码文件 )
add_executable(blkid_sd main.cpp)

执行命令:

mkdir build
cd build
cmake ..
make -j4
sudo ./blkid_sd
=> uuid is 007258df-98ea-47de-b906-35997ea63509

        关于c++获取硬盘/分区序列号,在Stack Overflow有一个类似的问题: c++ - Get HD/Partition serial number - Stack Overflow

猜你喜欢

转载自blog.csdn.net/weixin_34910922/article/details/131295089
今日推荐