How to import homepath into c program using gcc
Question
I am using gcc for windows. The OS is windows XP. How do I import the homepath variable into my c program so I can write to c:\%homepath%\desktop? I would like to use something similar to:
fd = fopen("C:\\%%homepath%%\\desktop\\helloworld.txt","w")
;
Solution
Use getenv() to get the value of an environment variable, then use sprintf or strcat to compose the path.
OTHER TIPS
Use getenv("homepath")
to get the value of environment variable. You should handle the case in which the variable has not been defined (getenv
returns NULL
in that case).
To compose the path use sprintf
char * homepath = getenv("homepath");
if(homepath == null) {
/* variable HOMEPATH has not been defined */
}
sprintf(path,"%s\\desktop\\helloworld.txt",homepath);
You should make path big enough to accomodate the value homepath
and \\desktop\\helloworld.txt
.
Also note the use of \\
in the string. You can't use single \
.
Note: you actually need to get the value of HOMEDRIVE as well, and prepend that to HOMEPATH. In many corporate environments, the home directories are kept on large network appliances or servers.