Hi, I made a writing to a .txt file program. It works fine, but, when I put it my .txt it just replaces that line of the texts in the .txt file. I was wanting know is there a way to go to the nexts line to write the new texts? Here my code:

There is probably a proper way to do this, but just off the top of my head, why don't you read the contents of the text file before writing? Then you could just append what you want to add to the file, and then replace the file with the new string.

03-21-2006

JaWiB

If you simply want to add to the end of a file, you can open it with the append flag:

Code:

std::ofstream out("somefile.txt",std::ios::app);

Otherwise, I think you will have to search through the file for the correct position, and use seekp to set the write position (no pun intended)

03-21-2006

adr

Ok I see what your saying joeprogrammer. You mean something like, openfile, save as a string, add strings togather, then that be the new string? I will try that, I didnt think of that.

JaWiB: LOL, I know you dont mean it as a pun but, I never use seekp. Could you show a small way to use it?

03-21-2006

JaWiB

AFAIK you can't just insert stuff in the middle of the file, you have to manually write over everything. Here's a little example:

int main ()
{
std::fstream file("test.txt",std::ios::in|std::ios::out);
std::string line;
std::string buffer;
std::streampos linepos;
bool found = false;
while (file>>line)
{
if (line=="Line2")
{
file.ignore();//ignore the endline character
linepos = file.tellg();//get this file read position
found=true;
}
else if (found)
{
buffer+=line+'\n'; //store what was after that line so we can rewrite it later
}
}
//we've hit the end of the file, so eofbit is set
file.clear(); //clear all the state flags
file.seekp(linepos); //find the pos where we want to insert
file<<"Line3\n"<<buffer; //write the line, then the rest of the text

}

03-21-2006

mabufo

Are you able to pass the '\n' bit, (I forget the word for it) to the text file? And by doing so, start on a new line?