Traversing backwords through a text file.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Studlyami
    Recognized Expert Contributor
    • Sep 2007
    • 464

    Traversing backwords through a text file.

    I have a text file which acts like an index to several other files. The text file contains <filename.txt >, <description for file name>. Every file listed in this index file contains data that i will format and display on the screen (using MFC). The user can select the next file, or goto the previous file. Right now what i do is i open the file read the items and create a map on my end that maps filename to the description. The map works, but it seems like it isn't necessary. I read the file using CStdiofile.read string() to read the next line of text. I was hoping there is a way to read the previous line of text. I've seen several functions that let you move backwards, but it requires a byte offset. Each file description can be any size . This index file is being used in a RTS and new entries get added to the bottom of the file (the file isn't a set amount of entries and the locations will change each time)

    A couple of questions:
    One can i read a previous line of text?
    Two If i read a line from the file is there a way to get the size (in bytes) of that line of text? Would the type of container i pass the string into matter (from the text file to CString?) This way i could just save the previous size of the string so i could use the offset functions (fseek, i don't remember what its called in the CFile class).
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Reading text files and traversing around presupposes you know the format of the file.

    For the traverse part, almost any positioning will be based on an offset from the start of the file, the end of the file, or the current position within the file. That means, your data has be placed just so.

    Therefore, is this a flat file? That is, one where all records are the same length.

    I assume is file is not encrypted or compresssed.

    If this isn't the case and your text file has records of variable length, you will be required to locate the start of each record- and remember it. That is, you read the previous record by changing the offset from the current position (or the start of the file) by a number of bytes that places you at the start of the previous record. It will extremely convenient if you just happen to have that value.

    The first record is at offset 0 and all other records begin with the character following the newline.

    When I have done this, I have always had a file with the record offsets for the records in another file. These offsets are usually associated with a key value. Usually I read the key/value pairs into an im-memory tree so I can access by key and find the offset to the data in the other file.

    Comment

    Working...