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

您所在的位置:网站首页 微信红包封面序列号获取方法 c++获取硬盘or分区序列号

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

2023-06-22 09:43| 来源: 网络整理| 查看: 265

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

GetVolumeInformation()

示例代码:

#include #include #include 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 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。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3