18

How would I find the driver letter of the main hard disk on a Windows Operating system?

That is, the drive with Program Files, System32, and so on.

3

5 Answers 5

32

There's an environment variable called SystemDrive which is set to the system drive (surprisingly enough). The getenv() call is how you can get to it.

char *sysDrive = getenv ("SystemDrive");
if (sysDrive == NULL) {
    // vote me down.
} else {
    // vote me up and use it.
}

This page lists a whole slew of environment variables available if you can't rely on specific directories existing on the system drive.

Alternatively, use the Windows API call, SHGetSpecialFolderPath(), and pass in the correct CSIDL. Then you shouldn't have to rely on the environment variables.

Although take note on those pages that this has been superceded by other functions in Vista (it should still work since this function becomes a wrapper around the new one).

0
5

The API Call GetWindowsDirectory could be of assistance. You can further parse this information using API's to parse the drive letter information.

2
  • What APIs would I use to "further parse" the GetWindowsDirectory() results?
    – unixman83
    Feb 13, 2012 at 2:33
  • Just get the first letter of the windows directory path.
    – Michael J
    Sep 16, 2012 at 7:40
2

SYSTEMDRIVE

PROGRAMFILES

SYSTEMROOT

WINDIR

Don't assume Program Files is on the same drive as Windows. It usually is. Usually.

1
  • 5
    You should mention that those in caps are names for Windows environment variables.
    – unixman83
    Feb 13, 2012 at 2:35
1

Get the system drive letter by using the function _dupenv_s .

getenv "Function is not thread safe [concurrency-mt-unsafe]" and "This function or variable may be unsafe. Consider using _dupenv_s instead." - VS2019 Compiler Warning (level 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);
}

Output:

system drive: C:
0

See Getting System Information on MSDN. It explains how to get system information in depth for the most part. very informative.

1
  • YOu need to format the answer with code tags and line breaks.
    – Alan
    Dec 24, 2017 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.