• Advertisement
Sign in to follow this  

File IO

This topic is 3485 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


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

Share this post


Link to post
Share on other sites
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";
}


Share this post


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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement