ofstream, find next line

Hi,

I would like to know how I can find the next available line in a text file using ofstream. For example, if I were to make a text-based game, I'd like to have one file with all of the items in the player's backpack, with item 1 being on line 1, item 2 being on line 2 etc. The problem here is, I don't know how to find the next available blank line in a text file to save the dude's new item to. This is just an example, I really have other intentions on what I will use this for. Does anyone know how I would go about writing a string of text to the next available new line in a text file? Thanks!!!!!!!
Here's my suggestion. When loading your program, read the whole file with all equipment into your memory. Manage it there. Then when you want to save or quit, replace the file with your new one.
How might I read the whole file? I am now having problems here. The best I can do is getline (in_stream, tmp) which only gives me the first line. Do you possibly know how I can read the whole file?
I hope the file isn't going to be massively huge.

There's an example of loading a file into memory here:
http://www.cplusplus.com/reference/iostream/istream/seekg/
closed account (zb0S216C)
awesomeprograms wrote:
how I can find the next available line in a text file using ofstream.

The end of a line is marked with the new-line character. Simply locate the first '\n' character. As the above posts suggested, load the file into buffer of some sort, then parse the file from there. It will allow you to remove unwanted data before parsing the data in it.

Wazzak
Thanks!!!! Now I have come to a final problem. In my example, I said I wanted to store the items in the backpack in the file. Now, say my character had multiple items, like food, and he ate one piece. how would I go about editing the line that file is located on?
Thank you for all your help, you'e been really helpful!
closed account (zb0S216C)
awesomeprograms wrote:
how would I go about editing the line that file is located on?

You can't. You'll have to pull the entire file back into memory, edit it, then send it back to the file. This is very inefficient. I recommend that you load the entire file into memory, run you program, and adjust the data if required when it's in the buffer. Before the program ends, overwrite the data in the file with the new data in the buffer.

Wazzak
Last edited on
Topic archived. No new replies allowed.