Automatically setting file path to user's desktop

Hi,

I have written a small program that basically takes a .txt file from the user's desktop and opens it for processing.

My issue is that the file path is currently hardcoded to my own deskop:

ex: "C:\\Users\\wboustany\\Desktop\\...

I want to work on other's computers as well, so I am trying to replace the "wboustany" by wathever is appropriate.

Now to find this replacement I have tried this code (that honestly I don't understand fully):

1
2
3
4
5
6
7
8
9
	wchar_t profilepath[250];
	ExpandEnvironmentStrings(L"%userprofile%",profilepath,250);
	//cout << profilepath; <--not working obviously

	size_t count;
	char *pMBBuffer = (char *)malloc( 250 );

	count = wcstombs(pMBBuffer, profilepath, 250 );
	cout << count; <-- yiels some odd number instead of "wboustany"


so what changes are needed to make this work. Assuming this work, will this deliver the result I intend ? i.e. count will store whatever the user is ?

Your help would be much appreciated.
Last edited on
You are printing a pointer so apparently you are seeing something like :

0x2983948

Right?

The code you are using tries to expaned the enviromental variable %userprofile%

Just open up cmd and type echo %userprofile%

Profit.
Thanks Silvermaul.

This indeed does produce the desired effect, but on the cmd console only...

How can I record that in a string ?

Thanks
std::string recordToAString(profilepath, profilepath + 250);
I don't really understand your last sentence.

Ok you are creating a string, but how to conciliate that with a dos command ?

or otherwise with a %userprofile% ?
Well

1
2
3
4
wchar_t profilepath[250];
ExpandEnvironmentStrings(L"%userprofile%",profilepath,250);
std::string recordToAString(profilepath, profilepath + 250);
std::cout<<"User profile is : "<<recordToAString<<std::endl;
Tried the code, something must be wrong I got garble output.

However I worked out another solution in the meantime, might help user:

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
	///KNOWING THE USERPROFILE
    char   psBuffer[128];
    FILE   *pPipe;

    if( (pPipe = _popen( "echo %userprofile%", "rt" )) == NULL )
       exit( 1 );

        // Read pipe until end of file. 
    while( !feof( pPipe ) )
    {
       if( fgets( psBuffer, 128, pPipe ) != NULL )
          cout << psBuffer;
    }

		//take out the space at the end of the text
	stringstream pipeLine;
	pipeLine << psBuffer;
	string extract;

	getline(pipeLine,extract);

        // Close pipe
	_pclose( pPipe );

	cout << extract;


Thanks you very much for your help anyway.
Well sorry I didn't actually tested it..

In any case here is a one liner:

1
2
std::string userProfile = getenv("userprofile");
std::cout<<userProfile<<std::endl;


Don't call dos when you don't need too :)
Last edited on
Thx will try your solution instead.

Regards,

W
Topic archived. No new replies allowed.