试图创建 ofstream 或 fopen 的程序崩溃

Program crashes trying to create ofstream or fopen

我没有足够的声誉点数来评论询问他们是否解决了最初提出的问题 here。我有同样的问题,程序在构建 ofstream 时崩溃。 不是多线程访问,但可以快速连续调用。我相信它会在第二次崩溃。我使用范围来确保流对象被销毁。 为什么会这样?

我也试过std::fopen。它还会导致崩溃。

这是使用 ofstream 的代码:

static bool writeConfigFile (const char * filename, const Config & cfg)
{
    logsPrintLine(_SLOG_SETCODE(_SLOGC_CONFIG, 0), _SLOG_INFO, "Write config file (%s stream)", filename);
    ofstream os(filename); // FIXME: Crashes here creating ofstream 2nd time
    if (os.good())
    {
        // Uses stream insertion operator to output attributes to stream 
        // in human readable form (about 2kb)
        outputConfig(cfg, os);
        if (!os.good())
        {
            logsPrintLine(_SLOG_SETCODE(_SLOGC_CONFIG, 0), _SLOG_NOTICE, "Failed to write configuration file (%s)", filename);
            return false;
        }
        logsPrintLine(_SLOG_SETCODE(_SLOGC_CONFIG, 0), _SLOG_INFO, "Configuration written to file (%s)", filename);
        return true;
    }
    logsPrintLine(_SLOG_SETCODE(_SLOGC_CONFIG, 0), _SLOG_NOTICE, "Cannot write configuration file (%s)", filename);
    return false;
}

/**
 * Called when configuration settings have been read/received and validated
 * @return true if successfully set, and written to file
 */
bool Config::set (SysConfigSource source, const struct SCADA_dsconfig * p)
{
    Lock lock(mtxSet); // This is locking a mutex on construction of the lock. Release it on destruction.
    // Setup the non-current one to switch to
    Config * pCfg = pConfig.other();
    unsigned i, f, n = 0;

    // set attributes in pCfg based on the config received
    // and some constants ...

    pCfg->setWritten(writeConfigFile("test.conf", *pCfg));

    if (!pCfg->isWritten())
    {
        // Don't set system config status here. Existing one still in use.
        logsPrintLine(_SLOG_SETCODE(_SLOGC_CONFIG, 0), _SLOG_NOTICE, "Config file not written. Retain prior config.");
        return false;
    }
    pConfig.swap(); // switch-in the new config
    setSystemConfigSource(source);
    toSyslog(pCfg);
    notifyConfigChange();
    return true;
}

也许 post 您的源代码的一部分,以便了解哪里出错了。

这是我将如何使用的非常基本的代码段 fstream.. 希望你会觉得它有用。

#include <iostream>
#include <fstream>
#include <string>

int main() {
    while (1) {
        std::string testString;
        std::ofstream outFile;
        outFile.open("Test", std::ios_base::app); // Appends to file, does not delete existing code

        std::cout << "Enter a string: ";
        std::cin >> testString;
        outFile << testString << std::endl;

        outFile.close();
    }
}

原来是设备驱动程序总线主控的问题。启动 devb-ahci 时添加 "ahci nobmstr"。

来自 http://www.qnx.com/developers/docs/qnxcar2/index.jsp?topic=%2Fcom.qnx.doc.neutrino.user_guide%2Ftopic%2Fhardware_Troubleshooting_devb-eide.html