0

这是我的代码


    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");

当我运行它时,我得到


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

当读取和写入 2 个文件成功时,我怎么可能遇到该错误?

通过注释掉我的 getPathFromUser() 函数来修复它,看起来像这样


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

4

1 回答 1

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

这是未定义的行为,因为您正在返回指向局部变量的指针。

于 2020-07-22T13:10:52.793 回答