syb0rg
syb0rg

Reputation: 8247

Why am I unable to create this file?

Here is my code example:

int main(int argc, char* argv[])
{
    char* fileName = "%appdata%\\log.log";
    FILE *file;
    file = fopen(fileName, "a+");
    time_t startTime = time(0);
    fputs("Started logging at: ", file);
    fputs(ctime(&startTime), file);
    fclose(file);
    printf("%s", fileName);
    return 0;
}

My program gets down to the printf() statement, and prints:

%appdata%\log.log

I know that is a viable location for a Windows computer, so why is the program unable to make the .log file? What is a workaround that I should use to make it work?

Upvotes: 0

Views: 239

Answers (2)

Anya Shenanigans
Anya Shenanigans

Reputation: 94859

the fopen call has no idea what %appdata% is, as it can't magically convert that into a path. You have to expand the path yourself using the ExpandEnvironmentStrings function. e.g. (untested):

char dest[MAX_PATH];
ExpandEnvironmentStrings(fileName, dest, MAX_PATH);
file = fopen(dest, "a+");

Upvotes: 4

A4L
A4L

Reputation: 17595

%appdata%

is an environment variable, they are not automatically resolved and need their values to explicitly be retrieved using getenv function call.

Upvotes: 4

Related Questions