Sign in to follow this  
chadsxe

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

Recommended Posts

chadsxe    146
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

Share this post


Link to post
Share on other sites
chadsxe    146
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

Share this post


Link to post
Share on other sites
raz0r    586
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();
}
};


Share this post


Link to post
Share on other sites
chadsxe    146
Alright...another dumb question....do I have to pre-put a .txt file in my project folder or will it automatically generate?

Share this post


Link to post
Share on other sites
xeddiex    238
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

Share this post


Link to post
Share on other sites
raz0r    586
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.

Share this post


Link to post
Share on other sites
xeddiex    238
Quote:
Original post by raz0r
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.


icic, thanks...

- xeddie

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this