Pelles C forum

C language => Beginner questions => Topic started by: davbaird on June 09, 2014, 04:15:54 PM

Title: Environmental variable %USERPROFILE%
Post by: davbaird on June 09, 2014, 04:15:54 PM
I'd like to use the %USERPROFILE% environmental variable as below.  But the file fails to open.  It works fine when I change fname to to the equivalent "C:\\Users\\Dave\\Documents\\hello.txt". Any ideas on how I can use %USERPROFILE% ?

#include <stdio.h>
int main(void)
{
   FILE *fp;
   char fname[] = "%USERPROFILE%\\Documents\\hello.txt";
   fp=fopen(fname,"w");
   if(fp!=NULL){
       fprintf(fp,"Hello, world!\n");
      fclose(fp);
   }
   else printf("can't open the file\n");
   return 0;
}
Title: Re: Environmental variable %USERPROFILE%
Post by: frankie on June 09, 2014, 04:26:41 PM
Retrieve the enviromental variable value using the function getenv.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
   FILE *fp;
   char fname[280];

   strcpy(fname, getenv("USERPROFILE"));
   strcat(fname, "\\Documents\\hello.txt");

   fp=fopen(fname,"w");
   if(fp!=NULL){
       fprintf(fp,"Hello, world!\n");
      fclose(fp);
    }
   else printf("can't open the file\n");
   return 0;
}
Title: Re: Environmental variable %USERPROFILE%
Post by: davbaird on June 09, 2014, 04:29:53 PM
Thanks!