NO

Author Topic: Environmental variable %USERPROFILE%  (Read 2753 times)

davbaird

  • Guest
Environmental variable %USERPROFILE%
« 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;
}

Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2113
Re: Environmental variable %USERPROFILE%
« Reply #1 on: June 09, 2014, 04:26:41 PM »
Retrieve the enviromental variable value using the function getenv.

Code: [Select]
#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;
}
« Last Edit: June 09, 2014, 04:28:17 PM by frankie »
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide

davbaird

  • Guest
Re: Environmental variable %USERPROFILE%
« Reply #2 on: June 09, 2014, 04:29:53 PM »
Thanks!