Need help with file I/O.......

Started by
9 comments, last by xeddiex 18 years ago
So I want to add logging to a program I have. I know the basics of file I/O but I am stuck on something.
void Engine::EnableLogging()
{
	//opens current file and destroys it contents
	ofstream a_file ( "logging.txt");
}

void Engine::WriteToLog()
{
	a_file << "Did my Implementation Work?" << endl;
	a_file.close();
}
I want to get EnableLogging() to open and clear a file, and upon exiting Enablelogging() I want the file to still be open so that I can write to it with WriteToLog(). As of now when the program exits EnableLogging() a_file looses scope which makes the use of it in WriteToLog() throw an error. Any suggestions... Thanks Chad
Advertisement
Make it a member variable.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Make a_file a member variable of your Engine class. Then it won't go out of scope until your Engine does.

Edit: Too slow
Little confusin....

So what your saying is remove ofstream a_file ("logging.txt");
and make it a private memeber variable of the engine class.

Thanks

Chad
Yes.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
They mean:

class CDummy{	std::ofstream a_file;	public:	CDummy(void);	~CDummy(void);	void EnableLogging(void)	{		this->a_file.open("logging.txt");	}	void WriteLog(void)	{		this->a_file << "Did my Implementation Work?" << std::endl;		this->a_file.close();	}};
Alright...another dumb question....do I have to pre-put a .txt file in my project folder or will it automatically generate?
Your log-file will be automatically generated when EnableLogging is called.
Quote:Original post by raz0r
They mean:

void EnableLogging(void)
{
this->a_file.open("logging.txt");
}

*** Source Snippet Removed ***

I have a question about this. Why can you not open a file via the a_file member itself: a_file("C:\\file.txt");, instead of invoking the member method, .open? I've notice the method I'm describing works outside of a class scope but not inside one, what's the reason?

Thanks,
- xeddiex
one..
Doing a_file(...) results in calling the appropriate constructor(if there is one based on what you pass). In a class for example, you declare your stream, and call open in your own constructor or member-function.

This topic is closed to new replies.

Advertisement