GMR
GMR

Reputation: 25

passing a pointer - for writing to a stream

Please excuse my ignorance.. i know a fair bit but am somehow still hazy on basics!?!Could you consider this simple example and tell me the best way to pass logmessages to '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;
}

Upvotes: 2

Views: 5220

Answers (1)

Dennis
Dennis

Reputation: 3731

Instead of an ofstream you need to use a FILE type.

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;
}

Where elsewhere

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

Or you can use ofstreams only.

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

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

Where elsewhere

m_oLogOstream( "MyLogFile.txt" );

Based on comment below what you seem to want to do is something like:

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;
}

Note that you really need more error checking than I have here, as you are dealing with c-style strings and raw pointers (both to the chars and the FILE).

Upvotes: 3

Related Questions