_wfopen_s返回2个不同的输出和2个相同的输入

时间:2019-01-28 08:27:47

标签: c++ visual-c++ c++17

当我输入_wfopen_s完全相同的字符串时,一个字符串,一个在运行时设置的字符串,该字符串成功,在运行时设置的字符串返回错误2(找不到文件或目录)

当我在Visual Studio调试器中查看“ buff”和“ bufftwo”时,它们包含的值完全相同,唯一不同的是地址。

2个缓冲区的顺序不会改变结果 。 它不是文件,目录或驱动器特定的。

我尝试从方法和变量中删除const,仍然会发生错误。

wchar_t* loadFileDialog() { //https://docs.microsoft.com/en-us/windows/desktop/learnwin32/example--the-open-dialog-box

    wchar_t buffer[255];

    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); 
    if (SUCCEEDED(hr))
    {
        IFileOpenDialog *pFileOpen;

        // Create the FileOpenDialog object.
        hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL,
            IID_IFileOpenDialog, reinterpret_cast<void**>(&pFileOpen));

        if (SUCCEEDED(hr))
        {
            // Show the Open dialog box.
            hr = pFileOpen->Show(NULL);

            // Get the file name from the dialog box.
            if (SUCCEEDED(hr))
            {
                IShellItem *pItem;
                hr = pFileOpen->GetResult(&pItem);
                if (SUCCEEDED(hr))
                {
                    PWSTR pszFilePath;
                    hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath);

                    // Display the file name to the user.
                    if (SUCCEEDED(hr))
                    {
                        lstrcpyW(buffer, pszFilePath); //Convert PWSTR into wchar array

                        CoTaskMemFree(pszFilePath);
                    }
                    pItem->Release();
                }
            }
            pFileOpen->Release();
        }
        CoUninitialize();
    }
    return buffer;
}
/*Loads a file into memory.*/
char* loadFile(const wchar_t* filePath) { 
    FILE *f;
    BOOL err = _wfopen_s(&f, filePath, L"rb");
    if (err == 0) {
        fseek(f, 0, SEEK_END);
        long fsize = ftell(f);
        fseek(f, 0, SEEK_SET);

        char *buff= (char *)malloc(fsize + 1);
        fread(buff, fsize, 1, f);
        fclose(f);

        buff[fsize] = 0;

        return buff;
    }
    else {
        //Outputs Err2, File not found. 
        throw std::runtime_error("error"); //Just here as a breakpoint until I make a better solution
    }
}
int main() {
    const wchar_t* bufftwo = loadFileDialog(); //Open Dialog Box
    const wchar_t* buff = L"C:\\Windows\\notepad.exe";

    if (lstrcmpW(bufftwo, buff) != 0) { //Here for testing, ensures both strings are identical.
        throw std::runtime_error("STRINGS ARE NOT THE SAME");
    }

    const char* myFile;

    myFile= loadFile(bufftwo);
    myFile= loadFile(buff);
}

我希望loadFile(bufftwo)和loadFile(buff)返回相同的值,因为它们具有相同的输入,但是loadFile(bufftwo)错误,而loadFile(buff)没有错误。

0 个答案:

没有答案