File IO

Started by
2 comments, last by fastcall22 15 years, 8 months ago
Need help with this code: #include <iostream> #include <fstream> using namespace std; int write(); int main() { write(); cout << "Contents written to file\n"; cin.get(); return 0; } int write() { ofstream log; log.open("log.txt", ios::ate); log << "File Opened"; log.close(); return 0; } What am i missing? I just want this code to post everytime i run it "File opened" in the file. Currently it posts it once and everytime i run the program it just has it once printed in the file. I want it to keep printing to the end of the file.... Daniel
Advertisement
	log.open("log.txt", ios::ate);


You should use "source", rather than "code", for your tags to get a code block.

As to your problem, I'm not exactly certain I understand what you want to do. Do you want to keep adding a line of text to the end of the existing file each time?

If so, you probably want to use ios::app rather than ios:ate.

Try this page for a more details look at reading/writing files in C++.

Alan
"There will come a time when you believe everything is finished. That will be the beginning." -Louis L'Amour
Also, the board markup [something_in_here] tags all use lowercase. will display as just that.

Anyway, things can and should be made much simpler, but yeah, the basic point is that you probably want the ios::app flag instead.

#include <iostream>#include <fstream>using namespace std;void write() {  ofstream("log.txt", ios::app) << "File Opened";}int main() {  write();  cout << "Contents written to file\n";}

Check to see if the ofstream is successful:

ofstream log;if ( !log.good() )	std::cout << "Not good.\n";


EDIT:
Misread the post. :|

[Edited by - _fastcall on August 3, 2008 10:58:59 PM]

This topic is closed to new replies.

Advertisement