LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Manipulation of text files in C++ (https://www.linuxquestions.org/questions/programming-9/manipulation-of-text-files-in-c-328430/)

Hady 05-30-2005 12:49 AM

Manipulation of text files in C++
 
Hi!

Could anyone tell me how I can add one line to the beginning of a text file using C++?
I know how to open/close/read from a text file, I just want adding one line without affecting any other content in the file..

Thank you for your time.

enemorales 05-30-2005 04:24 AM

I don't know if it can be done in other way, but one possibility is:

1.- open file.txt for reading and file.txt.bak for writing
2.- write a "\n" to file.txt.bak
3.- copy the content
4.- close the files
5.- remove file.txgt
6.- rename file.txt.bak to file.txt

step 5 shouldn't be very difficult. you only have to read from one file (which you know how to do) and write to the other, while the first file still has something inside.

jonaskoelker 05-30-2005 03:03 PM

I think he meant `one line', not `one newline', but that's a minor issue.

you could also do something along the lines of (pseudo-code):
Code:

stringbuffer b;
b.append("myline\n")
for char in filestream('file.txt'): b.append(char);
f = filestream('file.txt', 'w');
for char in b: f.write(char);
f.close();


Hady 05-31-2005 02:00 AM

OK!
Thank you guys for your help!

enemorales 05-31-2005 07:51 AM

Your pseudo-code looks a lot like python ;-)

jonaskoelker 05-31-2005 08:24 AM

Quote:

Your pseudo-code looks a lot like python ;-)
That's because python is runnable pseudo-code ;-)


All times are GMT -5. The time now is 11:53 PM.