Finding HOMEPATH - WinXP

I want to be able to access C:\Documents and Settings\Username, which under Environment Variables is HOMEPATH.

home.cpp:
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main()
{
    char *myhome = getenv("HOMEPATH");
	cout << "My home is: " << myhome << endl;
	return 0;
}


Output:
My home is: \


If I change "HOMEPATH" to "HOME":
My home is: C:\DEV\MSYS\home\Username

Which is the home directory of my development environment. How can I access my home directory in Windows XP?
HOMEPATH works for me. You could try USERPROFILE.
Thanks, USERPROFILE worked. I'm using the MinGW compiler, it's environment must interfere with some Environment Variables. Any ideas?
You could try looking at the output of this program to see what the environment looks like:

1
2
3
4
5
6
7
8
#include <iostream>

int main( int argc, char* argv[], char* env[] )
{
    for( ; *env; ++env )
        std::cout << *env << '\n';
    std::cin.get();
}

Never use environment variables (can be changed...)
Use Win32 Shell apis.
Never use Windows.
There is all can be changes :)
Never use environment variables (can be changed...)
Use Win32 Shell apis.

I'd say that's good advice. Here's a way to get the directory without using environment variables:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <windows.h>
#include <userenv.h>  // GetUserProfileDirectory() (link with userenv)

const int BUFLEN = 512;

BOOL getCurrentUserDir( char* buf, DWORD buflen ){
    BOOL ret;
    HANDLE hToken;

    if( !OpenProcessToken( GetCurrentProcess(), TOKEN_READ, &hToken ))
        return FALSE;

    if( !GetUserProfileDirectory( hToken, buf, &buflen ))
        return FALSE;

    CloseHandle( hToken );
    return TRUE;
}

int main( ){
    char buf[ BUFLEN ];
    if( !getCurrentUserDir( buf, BUFLEN )){
        std::cerr << "getCurrentUserDir failed" << std::endl;
        exit( 1 );
    }
    std::cout << buf << '\n';
}
Never use environment variables (can be changed...)
I'd say that's good advice.

It is always hard to justify blanket statements. The whole point is that environment variables can be changed. This can be exceedingly useful.

The choice whether to use environment variables or the Shell API depends entirely upon the problem set.

Hope this helps.
Topic archived. No new replies allowed.