Pointing back to previous file in directory

65 views Asked by At

Need to read preceding file name in directory.

When f_readdir function is run , the file name can be read and each time this function is run, it points to next file.

I want to read previous file name also. Basically keypad is connected with UP and Down functionality, so I want to give user an option to read previous file name also rather than just moving only foward.

1

There are 1 answers

0
Andrey Bienkowski On BEST ANSWER

Just like most other filesystem APIs fatfs only supports iterating the contents of a directory in one direction.

There are two common approaches to implementing the bi-directional traversal you want:

  1. Iterate the directory once from beginning to the end and store the names of all the files in an array. This gives you random-access to the entire list of names. Pseudocode (error handling omitted):
# Cache the file names in an array
files = []
for file in directory:
    files.append(file.name)
# Ask the user to choose a file
index = 0
while True:
    print(files[index])
    if <user pressed down>:
        index = index + 1
    elif <user pressed up>:
        index = index - 1
  1. Another solution that is less memory-intensive at the expense of being more CPU intensive is to remember the index of the current item and iterate the directory from the beginning when the user presses up or down. Pseudocode:
index = 0
while True:
    # Find file at index    
    <do f_opendir or maybe rewinddir>
    for i from 0 to index:
        file = <f_readdir>
    # Print the name of the file and ask the user what to do next
    print(file)
    if <user pressed down>:
        index = index + 1
    elif <user pressed up>:
        index = index - 1

You can also combine the two approaches. This might be more optimal at the expense of greater complexity.

Edit: the two fundamental techniques I tried to demonstrate here are: 1. caching. 2. rewinding and reading from the beginning. A simple implementation of caching caches the names of all the files in the directory. A simple implementation of rewinding always rewinds. A slightly more complex implementation of rewinding rewinds only when asked to iterate backwards.

A combined approach would be:

  1. Cache a small number of file names (e.g 21)
  2. When the user iterates past the end or past the beginning of the items you cached, update the cache by caching 21 file names centered on the currently selected file. Now the you don't have to update the cache again until the user presses up 10 times or down 10 times.

This combined approach is more complex, but it uses orders of magnitude less memory than the simple "cache everything" approach if a directory contains a sufficiently large number of files. This approach also cuts down the how often you have to rewind and start from the beginning by an order of magnitude compared to rewinding every time the user wants to iterate backward.