Default document folder path

Hi,

im trying to write a file to a default document folder
something like...

1
2
3
4
FILE* file;
file = fopen("%docdir%\\test.txt", "w");
fputs("Hello", file);
fclose(file);


"%docdir%\\test.txt" this isnt working for me, i have to write it as
"C:\\users\\public\\document\\test.txt"

any method to write directly to default document folder so it will work in most Windows ?

for example in windows 7 this is the default folder
"C:\\users\\public\\document\\test.txt"
in windows XP its different

i have to detect the windows version first, to write the correct path

thanks in advance
Looks like docdir is an environment variable. fopen() and other functions do not evaluate/expand environment variables.

For that, you will need to call getenv():
http://www.cplusplus.com/reference/cstdlib/getenv/

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <cstdlib>
#include <cstdio>
#include <string>

int main()
{
    //...
    char* docdir = getenv("docdir");
    if(docdir) // make sure it's not null.  It will be null if the environment variable is not found
    {
        std::string path = docdir;
        path +=  "/test.txt";

        FILE* file = fopen( path.c_str(), "w");
        //... 


Although in testing this... it doesn't look like "docdir" is an environment variable (at least not on my box). Where did you get that from?

I'm not sure which envionment var has the location of the documents folder. I'd have to look it up and I'm too lazy to do that right now.


EDIT: ok I'm an idiot. docdir was purely conceptual.

Sorry. =P You can probably disregard most of what I said above.

Hopefully someone else can chime in on this one.
Last edited on
Use SHGetFolderPath():

1
2
3
4
5
6
7
8
TCHAR path[MAX_PATH];
HRESULT hr = SHGetFolderPath(NULL, CSIDL_COMMON_DOCUMENTS, NULL,
                             SHGFP_TYPE_CURRENT, path);


if (FAILED(hr)) {
  // error message here
}


http://msdn.microsoft.com/en-us/library/bb762181%28VS.85%29.aspx

In windows XP this will return something like "C:\Documents and Settings\All Users\Documents", in windows 7 thgis will return something like "C:\Users\Public\Documents". There is no need to check windows version first.
thanks, both are working

1
2
3
4
5
        char* docdir = getenv("USERPROFILE");
	if(docdir)
	{
		string path(docdir);
		path += "\\Documents\\test.txt";



1
2
3
4
5
TCHAR path[MAX_PATH];
	HRESULT hr = SHGetFolderPath(NULL, CSIDL_COMMON_DOCUMENTS, NULL,
                             SHGFP_TYPE_CURRENT, path);
	string docdir(path);
	docdir += "\\test.txt";
Topic archived. No new replies allowed.