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