请原谅我的无知......我知道一点点,但我对某些基础知识仍然模糊不清!?!你能否考虑这个简单的例子并告诉我将logmessages传递给'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;
}
答案 0 :(得分: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+");
或者您只能使用ofstream。
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风格的字符串和原始指针(包括字符和文件)。