C++流:找不到输出文件

C++ ofstream: Can't find output file

本文关键字:输出 文件 找不到 C++      更新时间:2023-10-16

我已经创建了一个默认的 DirectX12 应用程序(旋转的 3D 立方体),在我的void DX::DeviceResources::Present()中,我正在尝试将后台缓冲区写入文件:

// Present the contents of the swap chain to the screen.
void DX::DeviceResources::Present()
{
    // The first argument instructs DXGI to block until VSync, putting the application
    // to sleep until the next VSync. This ensures we don't waste any cycles rendering
    // frames that will never be displayed to the screen.
    HRESULT hr = m_swapChain->Present(1, 0);
    UINT backBufferIndex = m_swapChain->GetCurrentBackBufferIndex();
    ComPtr<ID3D12Resource>         spBackBuffer;
    m_swapChain->GetBuffer(backBufferIndex, IID_PPV_ARGS(&spBackBuffer));
    //before writing the buffer, I want to check that the file is being 
    //created
    ofstream myfile;
    myfile.open("WHEREISTHEFILE.txt");
    myfile << "Writing this to a file.n";
    myfile.close();
    // If the device was removed either by a disconnection or a driver upgrade, we 
    // must recreate all device resources.
    if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
    {
        m_deviceRemoved = true;
    }
    else
    {
        DX::ThrowIfFailed(hr);
        MoveToNextFrame();
    }
}

问题出现在这里:

ofstream myfile;
myfile.open("WHEREISTHEFILE.txt");
myfile << "Writing this to a file.n";
myfile.close();

我只想先写一个文件(如图所示),然后再尝试写入后台缓冲区的内容。现在,由于某种原因,我找不到输出文件...我已经搜索了所有地方,我项目中的所有目录,甚至在Microsoft DirectX SDK文件夹中。

没有抛出异常,我可以在调试时单步执行每一行而不会出错。

可能在哪里?

它应该在项目的目录中。如果使用的是 Visual Studio,则可以右键单击解决方案,然后单击"在文件资源管理器中打开文件夹"。

图像:在文件资源管理器中打开文件夹

(我像这样嵌入它,因为我需要 10 个声誉才能直接发布图像)

此外,现在使用您的代码,无法确定您的程序是否真的能够打开输出文件。我建议你使用这样的东西:

std::ofstream outputFile("./myOutput.txt");
if (outputFile.fail())
{
    std::cout << "Failed to open outputfile.n";
}
outputFile << "I like trains.";
outputFile.close();

第一行是与 .open() 相同的初始化。还要注意路径前面的"./",这不应该是强制性的,但这样做不会有什么坏处(这意味着您当前的目录)。关于这段代码的重要部分是 .fail() 检查,如果您的程序无法打开输出文件,您当然无法在任何地方找到它。希望这有帮助!

可能在哪里?

通常文件位置是相对于您当前的工作目录的,即 WHEREISTHEFILE.txt应该位于启动程序时所在的任何目录中。

您可以通过 GetCurrentDirectory() 确定程序中的目录,并通过 SetCurrentDirectory() 将其更改为其他目录。

但是您没有检查.open()是否成功,因此写入可能完全失败,例如由于权限不足......?!