17

I am programming in C++ MFC and want to get the C:\windows and c:\program files paths programmatically.

Sometimes user may setup windows in other folder such as c:\windows0.

Is there any API to get absolute path of the windows and program files path?

5 Answers 5

29

Using Win32 API

For the Windows folder:

TCHAR windir[MAX_PATH];
GetWindowsDirectory(windir, MAX_PATH);

For program files:

TCHAR pf[MAX_PATH];
SHGetSpecialFolderPath(
    0,
    pf, 
    CSIDL_PROGRAM_FILES, 
    FALSE ); 

Where MAX_PATH comes from the Windows headers and will guarantee the buffer is long enough for the longest (non-UNC) path.

Also, note that SHGetSpecialFolderPath can be used to retrieve other "special" folder including the Windows folder just by replacing the third parameter to any from this list.

Sign up to request clarification or add additional context in comments.

1 Comment

The SHGetSpecialFolderPath function is no longer supported. For a modern solution see stackoverflow.com/q/35042967/2961550.
15

Comments

5

On Vista+, SHGetKnownFolderPath is the replacement for SHGetFolderPath and SHGetSpecialFolderPath, although you can continue to use the older functions if you need backward compatibility to older versions of Windows.

Comments

2

Call getenv("%ProgramFiles%") and getenv("%WinDir%").

3 Comments

I would not be dependent on environment variables.
Never trust Enivronment Variables. As they are accessible to user. He might change it.
As for SystemRoot (== %WinDir%) the story is a little different. Certain environment variables get not set via the registry but by the loader when creating a Win32 process.
2

Most of these come from SHGetFolderPath, but GetSystemDirectory() returns the absolute location of C:\Windows\System32. Don't use GetWindowsDirectory(). It doesn't do what you want anymore.

3 Comments

Would be more useful if you mentioned what aspect doesn't do anymore what the inquirer asked.
@0xC0000022L: "On a system that is running Terminal Services, each user has a unique Windows directory. "
Thanks. Okay, I was mostly worried about the "anymore". Terminal Services have existed since Windows NT and only became more mainstream with fast user switching in XP then ...

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.