请原谅我的无知......我知道很多,但不知何故,对基础知识仍然模糊不清?!您能否考虑这个简单的例子并告诉我将日志消息传递到"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;
}
您需要使用 FILE
类型而不是ofstream
。
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+");
或者您只能使用流。
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 argsn";
writeLogFile(m_pLogFile, ss.str().c_str() );
return 0;
}
请注意,您确实需要比我在这里更多的错误检查,因为您正在处理 c 样式字符串和原始指针(指向字符和 FILE)。