I am trying to count files. I have one hidden file from Windows10 so i am doing "-1" but I want to open the last file and can't work out how, any help? Please, Thanks

#include <SD.h>
int entryCount = 0;
File root;
int total = 0;
int Lfile = 0;
void setup()
{
  Serial.begin(9600);
  pinMode(10, OUTPUT);
  SD.begin(4);
  root = SD.open("/");
  printDirectory(root, 0);
  root.close();
  Serial.println();
  Serial.print(total-1);
  Lfile = total-1;

  File dataFile = SD.open(Lfile);
  // if the file is available, write to it:
  if (dataFile) {
    while (dataFile.available()) {
      Serial.write(dataFile.read());
    }
    dataFile.close();
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println();
    Serial.println("error opening last file");
  }
}

void loop()
{
  // nothing happens after setup finishes.
}

void printDirectory(File dir, int numTabs)
{
  while (true)
  {
    File entry = dir.openNextFile();
    if (! entry)
    {
      if (numTabs == 0)
      return;
    }
    for (uint8_t i = 0; i < numTabs; i++)
      Serial.print('\t');
    Serial.println(entry.name());
    total = entryCount;

    Serial.print(entryCount++);

    Serial.print('\t');

    entry.close();


  }
}
  • what does last file mean? – jsotola Jul 10 at 23:51
  • sd card have files log01.txt, log02.txt, etc. Last file is last file which was created – Egauss Egauss Jul 11 at 0:19

Consider using the exist() method found in the SD.h library you already are including in your program. Assuming you will create no more than 99 files and the last file created will have the highest 2 digit value as part of its name, test for the existence of the file log99.txt. If not found, decrement the 2 digit number and test for the existence of file log98.txt. Repeat this process until you find the newest file created.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.