本文提供 C 语言代码示例,分别演示在 Windows 和 Linux 系统中如何获取所有硬盘的信息。

  1. 使用 Windows API:
#include <Windows.h>
#include <stdio.h>

int main() {
    DWORD drives = GetLogicalDrives();
    char driveLetter = 'A';

    while (drives) {
        if (drives & 1) {
            char drivePath[4];
            sprintf(drivePath, "%c:\", driveLetter);

            printf("Drive: %s\n", drivePath);
        }

        drives >>= 1;
        driveLetter++;
    }

    return 0;
}
  1. 使用 Linux 系统调用:
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>

int main() {
    struct dirent *entry;
    DIR *dir = opendir("/dev");

    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

    while ((entry = readdir(dir)) != NULL) {
        struct stat statbuf;
        char path[256];

        snprintf(path, sizeof(path), "/dev/%s", entry->d_name);

        if (stat(path, &statbuf) == 0 && S_ISBLK(statbuf.st_mode)) {
            printf("Drive: %s\n", path);
        }
    }

    closedir(dir);

    return 0;
}

以上代码分别演示了在 Windows 和 Linux 系统中获取所有硬盘的方法。在 Windows 中,我们使用 GetLogicalDrives 函数获取逻辑驱动器的位掩码,然后逐位判断该位是否为 1,根据位的位置确定驱动器号。在 Linux 中,我们使用 opendir 和 readdir 函数遍历 /dev 目录下的所有文件,然后通过 stat 函数获取文件的属性,判断是否为块设备文件,从而确定是硬盘。

C语言获取所有硬盘信息:Windows 和 Linux 代码示例

原文地址: https://www.cveoy.top/t/topic/fwIM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录