Search code examples
cfopen

Create file and save it as current logged in username.txt using C programming


I want to create a file with C and save it as the current logged in "username".txt

For example: if the current user is bob, when the runs the program it create a file named "bob.txt" under "c:\users\bob\MAP\" directory

The code I have below saves a file data.txt under "c:\users\bob\MAP\" directory. However i want to make the saved file as "bob.txt" given that he is the current logged in user executing the program.

char oBuffer[MAX_PATH];
memset(oBuffer, 0, MAX_PATH);
ExpandEnvironmentStrings("%userprofile%", oBuffer, MAX_PATH);
strcat(oBuffer, "\\MAP\\");
CreateDirectoryA(oBuffer, 0);
strcat(oBuffer, "data.dat");
strcpy(LOG_PATH, oBuffer); 

logfile = fopen(("%s.dat", getenv("USERPROFILE")), "a+");

I would like to have "c:\users\bob\MAP\bob.txt" create on execution of the program.

Thanks in advance


Solution

  • just use the name already copied to oBuffer

    // ... UNTESTED CODE
    ExpandEnvironmentStrings("%userprofile%", oBuffer, MAX_PATH);
    // assume "C:\Users\username"
    //         0123456789 username starts at position 9
    int userpos = 9; // TODO: better user strrchr()
    int uplen = strlen(oBuffer); // username ends at the end of the string
    strcat(oBuffer, "\\MAP\\"); // oBuffer now has "C:\Users\username\MAP\"
    CreateDirectoryA(oBuffer, 0);
    //strcat(oBuffer, "data.dat");
    sprintf(oBuffer, "%s%.*s.txt", oBuffer, uplen - userpos, oBuffer + userpos);
    // oBuffer now has "C:\Users\username\MAP\username.txt"
    // ...