Hi, It's me again with another silly question:)
I was wondering if there was a way using ofstream to not erase the contents of the file it is writing to and simply write at the end.
Thanks!
P.S. I'm using windows XP and Dev C++

Dani AI

Generated

Quick follow-up to the thread: pointed you in the right direction — the file should be opened with a non‑truncating mode so existing bytes are preserved. A few practical notes that often confuse people later on.

By default a plain std::ofstream is opened for output in a way that will truncate the file. If you want to keep what's already there, open with a mode that prevents truncation and check the stream after opening. Use std::fstream when you need both reading and writing. Also be aware of the subtle difference between two end-of-file behaviors: one moves the write position to the end only once when opened (allowing later seeks), the other forces every write to go to the end regardless of seeks. The standard flags and their exact semantics are documented on cppreference: std::ios_base::openmode and the ofstream constructor details are here: std::basic_ofstream::basic_ofstream.

Example patterns (check for errors and include <fstream>):

std::ofstream ofs;
ofs.open("example.txt", std::ios_base::out | std::ios_base::app);
if (!ofs) { /* handle error */ }
ofs << "Add this line\n";
std::fstream fs("example.txt", std::ios_base::in | std::ios_base::out | std::ios_base::ate);
if (fs) {
  // initially at end but can reposition
  fs << "Another line\n";
}

Troubleshooting tips: confirm the stream opened (operator bool or is_open()), verify file permissions or other locks (other programs can lock files on Windows), and close or flush the stream when done so data isn't lost if the program exits unexpectedly. This covers common pitfalls beyond the quick fix suggested to .

Recommended Answers

All 3 Replies

ofstream myfile("example.txt", std::ios::app);

Hope that helps :P
app stands for append btw

Chris

Thanks

Your Welcome,
Go ahead and mark this as solved.

Chris

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.