Environmental variable %USERPROFILE%

Started by davbaird, June 09, 2014, 04:15:54 PM

Previous topic - Next topic

davbaird

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;
}

frankie

#1
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;
}
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide