Serial/Random Access File

Hi. I am extremely new to C++ and have my first year final assignment to complete. I'm rather stuck.

Is it possible to add to each individual line in a serial text file and save it in the file or does it need to be a random access file? I am really hoping that it can be done in a serial file as I can't get my head around random access.

Thanks very much.
I don't know exactly what you want, but if the file is not too big you can always read it completely manipulate it and write it back. Random access is good for huge files like databases.
Thank you very much. I am going to have a go at that and see how it goes.
Most of the time, a text file requires serial access due to the variable length of the data (strings or lines) that you are inserting

However, if you are able to turn any variable length data into fixed length data through preprocessing, you may use a random access file (aka binary file) instead

For example, say you know for sure that in your text file, you can ensure that a line will always contain less than 80 characters. You can, then define a record as an array of 80 characters.

That means if you have less than 80 characters in your actual line, you still write out 80 characters (padding the right side with spaces or something else). If you have more than 80 characters, you will have to to truncate or break it up.

Ignoring these details for a moment, with a fixed record size of 80 characters, you ran randomly access the first line (offset 0 from beginning of file), the second line (offset 79), or the nth line (offset (n-1)*80-1).

This means you can jump to the nth line without having to read the previous lines.
(the definition of random access)

The principle is to convert whatever variable length data you have into records of fixed length before writing them to disk.

How you do this is up to the specific task and up to your design.

edit: I think this is actually an excellent final project - often, one of the bottlenecks of a fast program is File I/O - knowing how to write and read random access files is a great way around this bottleneck
Last edited on
Topic archived. No new replies allowed.