Increment Files with SD

I am using an Arduino and microSD card to create a new file in a directory every time the Arduino powers on.

My code is as follows:

    if (SDDetect) {
      //// Count the amount of Files in the LogFiles Directory ////
      countFile = SD.open("LogFiles/");
      while (true) {
        File entry =  countFile.openNextFile();
        if (! entry) {
          break;
        }
        fileCount++;
      }
      fileCount++; //Add one to fileCount to creat the next file

      //// Create a new file ////
      String FileName =  String("LogFiles/Log0") + fileCount + String(".csv");
      
      logFile = SD.open(FileName, FILE_WRITE);
      logFile.println("Header1, Header2, Header3, Header4, Header5, Header6, Header7, Header8");
    }

This code works great the first time I run the code! Creates the file Log01.csv in the LogFiles directory, and writes the header to the CSV. I turn the Arudino off and turn it back on, and it creates another file Log02.csv and writes the header.

The issue is when I create a 3rd file. It creates Log03.csv and then freezes. I open up the SD card on my computer and it creates the file but did not write the header. If I delete the files in the directory and start again the same thing happens. Works great the first two times and then freezes on the 3rd. Any ideas as to why this is happening? Or is there any easier way to do what I am trying to achieve?

OpenNextFile does indeed open the file, which consumes RAM, so when you have enough open, you run out. You need a corresponding close.

I added a close function to the while loop.

      //// Count the amount of Files in the LogFiles Directory ////
      countFile = SD.open("LogFiles/");
      while (true) {
        File entry =  countFile.openNextFile();
        if (! entry) {
          break;
        }
        entry.close();
        fileCount++;
      }
      fileCount++; //Add one to fileCount to creat the next file

      //// Create a new file ////
      String FileName =  String("LogFiles/Log0") + fileCount + String(".csv");

      logFile = SD.open(FileName, FILE_WRITE);
      logFile.println("Header1, Header2, Header3, Header4, Header5, Header6, Header7, Header8");

This code does work and creates files with headers every time I turn the Arudino on. But now I am having the issue when there are more than two files it takes an incredibly long time to create another file and write the header. About 10 seconds.

I have a similar requirement but took a different approach.
I start with a file name (w/o extension) of 100,
I add the extension .cvs
I look to see if the file 100.cvs exists
If it does I increment 100 then look for 101.cvs etc

my code is:

  do
    {
     itoa(gFileNumb, gDataFile, 10);  // (value, Array, base)
     const char *extension = ".csv";
     strcat(gDataFile, extension);  // syntax:  strcat(dest, source)
     ++gFileNumb;
    } while (SD.exists(gDataFile));  // assume will Rtn false if  no communication.