如何在Windows操作系统上找到主硬盘的驱动器字母?
换句话说,就是那个带有Program Files
、System32
等文件夹的硬盘。
如何在Windows操作系统上找到主硬盘的驱动器字母?
换句话说,就是那个带有Program Files
、System32
等文件夹的硬盘。
有一个名为SystemDrive
的环境变量,它被设置为系统驱动器(出乎意料吧)。您可以使用getenv()
函数来获取它。
char *sysDrive = getenv ("SystemDrive");
if (sysDrive == NULL) {
// vote me down.
} else {
// vote me up and use it.
}
此页面列出了大量的环境变量,如果您不能依赖于系统驱动器上存在特定目录,则可以使用它们。
或者,使用Windows API调用SHGetSpecialFolderPath()并传递正确的CSIDL。然后,您就不必依赖于环境变量。
尽管请注意这些页面已被 Vista 中的其他函数取代(因为此函数将成为新函数的包装器),但它仍应该能够工作。
GetWindowsDirectory()
的结果? - unixman83系统驱动器
程序文件
系统根目录
Windows目录
不要假设程序文件和Windows安装在同一驱动器上。它通常是这样。通常。
使用函数_dupenv_s
获取系统驱动器字母。
getenv
"函数不是线程安全的[并发-mt-unsafe]"和"此函数或变量可能不安全。请考虑改用_dupenv_s。" - VS2019编译器警告(级别3)C4996。
#include <iostream>
int main()
{
char* system_drive{ nullptr };
size_t count{ 0 };
// _dupenv_s is a Microsoft function, designed as a more secure form of getenv:
_dupenv_s(&system_drive, &count, "SystemDrive");
std::cout << "system drive: " << system_drive << std::endl;
// Note: It is the calling program's responsibility to free the memory by calling free:
free(system_drive);
}
输出:
system drive: C: