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.
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:
# 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
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:
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.