Problem with writing to file
Aug 11, 2012 at 1:06pm UTC
I'm trying to make a logger thing for a game engine that logs the important things that happen and errors too.
I ahve this code:
1 2 3 4 5 6
void Log(char * input)
{
FILE* log = fopen("engine.log" , "a" );
fwrite(input, sizeof (input), 1, log);
fclose(log);
}
but when i do for example Log("foo is working"); it only outputs the word "foo " to the file. How could i work around this?
Aug 11, 2012 at 1:23pm UTC
sizeof(char*) always returns 4 on x86 platforms. Pass the buffer size to your function as another argument (do not use strlen() if you are working with binary data).
Aug 11, 2012 at 1:30pm UTC
If you are not working with binary data, consider using fputs()
Aug 11, 2012 at 1:31pm UTC
How i could get the buffer size?
Aug 11, 2012 at 1:37pm UTC
You created the buffer, ¿don't you?
Aug 11, 2012 at 3:05pm UTC
I dint create any buffers. I just call that log function with a string and then it should write it to a log file.
Aug 11, 2012 at 3:09pm UTC
If this is C++
1 2 3 4 5 6 7 8
#include <fstream>
#include <string>
void log( const std::string& message, const std::string& path2file = "engine.log" )
{
std::ofstream log( path2file /*.c_str()*/ , std::ios_base::app ) ;
log << message << '\n' ;
}
else if C
1 2 3 4 5 6 7 8 9 10 11 12
void log( const char * message ) // being const-correct
{
if ( message != NULL )
{
FILE* log = fopen( "engine.log" , "a" ) ;
if ( log != NULL )
{
fputs( message, log ) ;
fclose(log) ;
}
}
}
Aug 11, 2012 at 3:19pm UTC
Thanks JLBorges! Now its working perfectly with slight adjustments :)
Topic archived. No new replies allowed.