有时在调用fcout时出现未处理的异常

时间:2015-11-30 21:31:22

标签: c++

我有这个函数将一些日志信息写入文件

int Comm::saveInfo(LPTSTR msg)
{
#ifdef _log
    wofstream fcout(LogFile, ios::out | ios::app);
     if (fcout.is_open())
     {

        fcout << msg << "\t" << (int) ::GetTickCount64() << endl;
        fcout.close();
     }
#endif
    return 0; // this is where visual studio 2012 is pointing to for the crash
}

此功能有时有效,但有时会崩溃...... :(

以下是我如何调用此函数:

saveInfo(TEXT("set measurement time..."));
ret = readMsg(Buf, WAITTIMOUT);

Comm类的头文件中,我将std::wstring LogFile;声明为私有成员。 readMsg是读取管道的函数

int CpipeComm::readMsg(LPTSTR chBuf, DWORD timeout)
{

    OVERLAPPED overlapped;
    memset(&overlapped, 0, sizeof(overlapped));
    memset(&chBuf[0], 0, sizeof(chBuf));

    int err = 0; 
    ULONGLONG time1 = ::GetTickCount64();
    DWORD bytesRead = 0;
    do 
    { 
   // Read from the pipe. 
      fSuccess = ReadFile( 
         hPipe,    // pipe handle 
         chBuf,    // buffer to receive reply 
         BUFSIZE*sizeof(TCHAR),  // size of buffer 
         &cbRead,  // number of bytes read 
         &overlapped);    // not overlapped 

return 0;
}

在Comm类的构造函数中我做了

 LogFile.assign(L"Pipe_log.log");

我得到的随机错误是

Unhandled exception at 0x000007FEF782AFD3 (msvcp110.dll) in : 0xC0000005: Access violation reading location 0x0000000000000012.

我不确定是否有什么我做错了!不知何故,这两个功能一个接一个地导致崩溃!如果我将saveInfo函数移到另一个地方,那么一切正常......

1 个答案:

答案 0 :(得分:1)

没有有效的文件流构造函数,它以std::wstring作为文件名。看起来这是LogFile的类型,基于您的初始化示例。

您应该像这样构建流:

wofstream fcout( LogFile.c_str(), ios::out | ios::app );