From 6d4bc9a1f847d51047814583834c5a4cbfeb2ae6 Mon Sep 17 00:00:00 2001
From: GMagician <3684609+GMagician@users.noreply.github.com>
Date: Fri, 26 Jan 2018 21:03:51 +0100
Subject: [PATCH] [2.0.x] Fix SD wrong filename list (#9342)

If last file in directory has short filename and is preceded by a deleted long file name. SD menu will wrongly report long deleted file name as last entry
---
 Marlin/src/sd/SdBaseFile.cpp | 14 +++++++++-----
 1 file changed, 9 insertions(+), 5 deletions(-)

diff --git a/Marlin/src/sd/SdBaseFile.cpp b/Marlin/src/sd/SdBaseFile.cpp
index ddde1d0d1f..1cf1e0ad6d 100644
--- a/Marlin/src/sd/SdBaseFile.cpp
+++ b/Marlin/src/sd/SdBaseFile.cpp
@@ -1054,8 +1054,9 @@ int8_t SdBaseFile::readDir(dir_t* dir, char* longFilename) {
   // if not a directory file or miss-positioned return an error
   if (!isDir() || (0x1F & curPosition_)) return -1;
 
-  //If we have a longFilename buffer, mark it as invalid. If we find a long filename it will be filled automaticly.
-  if (longFilename != NULL) longFilename[0] = '\0';
+  // If we have a longFilename buffer, mark it as invalid.
+  // If long filename is found it will be filled automatically.
+  if (longFilename) longFilename[0] = '\0';
 
   while (1) {
 
@@ -1065,12 +1066,15 @@ int8_t SdBaseFile::readDir(dir_t* dir, char* longFilename) {
     // last entry if DIR_NAME_FREE
     if (dir->name[0] == DIR_NAME_FREE) return 0;
 
-    // skip empty entries and entry for .  and ..
-    if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') continue;
+    // skip deleted entry and entry for .  and ..
+    if (dir->name[0] == DIR_NAME_DELETED || dir->name[0] == '.') {
+      if (longFilename) longFilename[0] = '\0';     // Invalidate erased file long name, if any
+      continue;
+    }
 
     // Fill the long filename if we have a long filename entry.
     // Long filename entries are stored before the short filename.
-    if (longFilename != NULL && DIR_IS_LONG_NAME(dir)) {
+    if (longFilename && DIR_IS_LONG_NAME(dir)) {
       vfat_t* VFAT = (vfat_t*)dir;
       // Sanity-check the VFAT entry. The first cluster is always set to zero. And the sequence number should be higher than 0
       if (VFAT->firstClusterLow == 0) {