How can I choose where in a file I write?

Hello,

I would like to write to a file using fstream, but I would like to know how I can write to a specific location. Say I draw out a 10x10 matrix in my file but then I would like to draw out another matrix to its right, or left. Or say I'd like to draw out another matrix above or below the previous one. How can I do this?
I feel like I remember learning something about this, but I don't exactly remember. Any help would be amazing. Thank you!
binary files, if designed correctly, let you hop around inside them very easily and efficiently to go from one entity to another and then drill down inside the "record" to the exact single POD type you want to read or change.

Text files are a bit more trouble. Text files are of course a subset of binary files, and all the above tricks work on them if they are formatted to a fixed width format, but most text files are random width and much more aggravating to use for this type of access.

So my first instinct is to advise you to use a binary file here. However if you are trying to make a text file, you will need other tricks.

As for actually doing it, look at the seekg member of fstream for the binary approach.

For a text approach, you have to figure out what you want to do... fixed widths with space padding would work, or delimiters like | or such symbols would work... lots of ways, but you have to design something.
Last edited on
Thank you very much!
Jonnin is correct; however, I'd like to ask you what are you trying to capture in your file? Are you wanting to create a 10 X 10 matrix to display? If so, think about this idea:

If you want to keep the file to a smaller size, perhaps you could save coordinates in your file. Maybe points on a line, like row 3, column 9, for a starting coordinate and row 5, column 20 for the ending coordinate, etc. You would then need code to read the numbers from the file and then draw the matrix using the data.

Just something to think about ...

Good luck!
Topic archived. No new replies allowed.