SD FS dropping filenames

Hi Folks,
I have a Mega with a Adafruit 1.8" TFT screen with Joystick and SD card interface. I have developed a simple menu system for selecting files by putting a list of up to 10 files onto the TFT at a time, and paging further lots of 10 (or less) at a time to show more files. Only 10 file names are shown at any one time (I do not want to use Folders at this stage).

I have included a shortened version below without TFT and a lot of other stuff, however it still exhibits the problem:
Each time a file is loaded (which is always successful), file name entries, up to and including the selected file are missing when the list of files is reloaded.

If the file list is reloaded 5 times consecutively it is fine, and if a selected file is loaded 5 times that is OK as well. The error only occurs when I list the files on the SD card, select one, say the first file, and load it into memory. When the list of files is fetched again, in this example the first file name will be missing from the list. If I select the third file, files 1st,2nd,3rd will be missing from the next list of files, and so on. (A dump of the serial debug is provided).

If it lies in my simplistic programming to extract names of files into a character array for use as a simple screen buffer I apologise in advance, and would appreciate any assistance in streamlining this.

If anyone can cast some light on this problem, I will be very grateful.

Cheers, Rob
PS I updated my SD library to GitHub - adafruit/SD: fixes & updates to the Arduino SD library - totally in progress. works but in beta

SD_Dump.txt (3.81 KB)

SD_Tester.ino (5.1 KB)

You must rewind the directory if your code uses openNextFile.

See this topic http://forum.arduino.cc//index.php?topic=190889.msg1411300#msg1411300

There are many other posts for this problem.

Thank fat16lib,
It is now working. I enclose the altered code below, and include a snippet here to highlight the important bit.

 <snippet>  
  int pageBegin = 10*page; //find files in groups of 10
  int pageEnd =pageBegin+10;
  int entryNos=0; //zero referenced pages page0 is first page
  File SdFs = SD.open("/"); //Treats each opening file as a file
  SdFs.rewindDirectory();//make sure we start at the START of the folder each time.
  File entry = SdFs.openNextFile(); //get first entry in folder to begin with, assume at least one file???
  while (entry) { //keep getting entries while they exist on SD card
    if ((entryNos>=pageBegin)&&(entryNos<pageEnd)){ //Process if they fall into the right page limits
      Serial.println(entry.name());
      ................

Keeping the file name pointer at a preserved position certainly makes recursive searching of folders etc on the card easier, but it was a problem for me. Another half a day looking for non existent (or yet to be found) memory leaks.

Oh Well, thanks again,

Rob

SD_Tester.ino (5.1 KB)