0

here is my code


    FILE * paths = fopen(CONFIGS_TXT, "r");
    FILE * temp = fopen(TEMP_FILE, "w");

    fgets(buf, 100, paths);
    token = strtok(buf, "=");
    token = strtok(NULL, "\n");
    if(token == NULL) {
        token = getPathFromUser();
    }
    fprintf(temp, "DOLPHIN_PATH=%s\n", token);

    fclose(paths);
    fclose(temp);
    
    errno = 0;
    remove(CONFIGS_TXT);
    perror("The following error occurred");

    errno = 0;
    rename(TEMP_FILE, CONFIGS_TXT);
    perror("The following error occurred");

when i run it i get


The following error occurred: No such file or directory
The following error occurred: No such file or directory

how is it even possible for me to get that error when reading and writing to the 2 files was successful?

it is fixed by commenting out my getPathFromUser() function which looks like this


char * getPathFromUser() {
    
    OPENFILENAME ofn;
    char fileName[MAX_PATH] = "";
    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(OPENFILENAME);
    ofn.hwndOwner = NULL;
    ofn.lpstrFilter = "executables (*.exe*)\0*.exe*\0";
    ofn.lpstrFile = fileName;
    ofn.nMaxFile = MAX_PATH;
    ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
    ofn.lpstrDefExt = "";

    char * filePath;

    if(GetOpenFileName(&ofn))
        filePath = fileName;

    return filePath;
}

Xyrho
  • 21
  • 3
  • Try reading the man page for remove. – Fredrik Jul 22 '20 at 11:26
  • Could you provide a [MCVE]? – Jabberwocky Jul 22 '20 at 11:36
  • 3
    You have to check if the return value of `remove()` is -1 before evaluating `errno`. If the return value is 0, the value of `errno` is undetermined. Internal libc calls may set it to some value that has nothing to do with the overall success of the `remove()` call. Apart from the error messages, does the program work as expected? – Ctx Jul 22 '20 at 11:48
  • the program does not work as expected, but commenting out my getPathFromUser() function causes it to work properly again. All that function does is call the [GetOpenFileName](https://learn.microsoft.com/en-us/windows/win32/api/commdlg/nf-commdlg-getopenfilenamea) function. – Xyrho Jul 22 '20 at 12:06
  • I figured it out. This was a problem caused by the GetOpenFileName() function. To fix, simply just add the OFN_NOCHANGEDIR to ofn.flags. Apparently it changes the current folder for your process, which it doesn't mention anywhere in the page i linked. All of the code pertaining to remove/rename was implemented correctly. – Xyrho Jul 22 '20 at 12:17

1 Answers1

0
char fileName[MAX_PATH] = "";
...
char * filePath;
...
filePath = fileName;
...
return filePath;

This is undefined behaviour as you are returning a pointer to a local variable.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243