2

请原谅我的无知..我知道一些,但不知何故仍然对基础知识感到模糊!?!你能考虑这个简单的例子并告诉我将日志消息传递给'writeLogFile'的最佳方法吗?

void writeLogFile (ofstream *logStream_ptr) 
{  
    FILE* file;
    errno_t err;

    //will check this and put in an if statement later..
    err = fopen_s(&file, logFileName, "w+" );


    //MAIN PROB:how can I write the data passed to this function into a file??

    fwrite(logStream_ptr, sizeof(char), sizeof(logStream_ptr), file);


    fclose(file);

}

int _tmain(int argc, _TCHAR* argv[])
{

    logStream <<"someText";

    writeLogFile(&logStream); //this is not correct, but I'm not sure how to fix it

    return 0;
}
4

1 回答 1

3

而不是ofstream你需要使用FILE类型。

void writeLogFile ( FILE* file_ptr, const char* logBuffer ) 
{  
   fwrite(logBuffer,1, sizeof(LOG_BUF_MAX_SIZE), file);
}

int _tmain(int argc, _TCHAR* argv[])
{
    writeLogFile(m_pLogFile, "Output"); 
    return 0;
}

在别处

m_pLogFile = fopen("MyLogFile.txt", "w+");

或者您只能使用 ofstreams。

void writeLogFile ( const char* logBuffer ) 
{  
   m_oLogOstream << logBuffer << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    writeLogFile("Output"); 
    return 0;
}

在别处

m_oLogOstream( "MyLogFile.txt" );

根据下面的评论,您似乎想要做的是:

void writeLogFile ( const char* output) 
{  
    fwrite(output, 1, strlen(output), m_pFilePtr);
}

int _tmain(int argc, _TCHAR* argv[])
{
    stringstream ss(stringstream::in);
    ss << "Received " << argc << " command line args\n";
    writeLogFile(m_pLogFile, ss.str().c_str() ); 
    return 0;
}

请注意,您确实需要比我这里更多的错误检查,因为您正在处理 c 样式的字符串和原始指针(指向字符和文件)。

于 2012-06-07T09:38:00.653 回答