problems with file counting after writing on SD Card

Dear All,
I’m new in the Arduino World. Maybe already somebody else has posted the same problem already before, but on my research on the forum as well as on googling I could found no idea, what I’m doing wrong. Maybe someone finds my mistake.

The Aim of the small Project:
I have a Button and an SD-Card Modul.
I push the Button and Arduino counts the files on the SD card and writes a textfile with the name count+1

The Problem:
When I push the button the first time it works like it should.
If I push it the second + time, the counting does not work (gives 000.txt)

Trials:
If I let run the writing before the counting it also does not count right.

Question:
Why is this like this?
What did I wrong?
How can I bypass this?

Thanks a lot in advance for your support and help

Attached my code.

//Button 1
const int buttonPin1 =2;     // the number of the pushbutton pin
int buttonState1 = 0;         // variable for reading the pushbutton status

//SD Card
#include <SD.h>
const int chipSelect = 10;


void setup()
{
 Serial.begin(9600);

//Button 1
    pinMode(buttonPin1, INPUT); // initialize the pushbutton pin as an input:

//SD Card
   Serial.print("Initializing SD card...");
   pinMode(10, OUTPUT);
   // see if the card is present and can be initialized:
   if (!SD.begin(chipSelect)) {
     Serial.println("Card failed, or not present");
     return;
   }
   Serial.println("card initialized.");
}


void loop()
{
  //Button1
  buttonState1 = digitalRead(buttonPin1);
  // check if the pushbutton 1 is pressed.
  if (buttonState1 == 1){
    String filename=sdFilecount();
    writeonSD(filename); 
    } 
  delay (500); 
}



void writeonSD(String filename){
 String dataString="This is a Test";
 
 File dataFile = SD.open(filename, FILE_WRITE);
 if (dataFile) {
   dataFile.println(dataString);
   dataFile.close();
   Serial.println("File Written");
 }  
 dataFile.close();
  
}

String sdFilecount( ) {
  File dir = SD.open("/");
  int numTabs=0;
  int countfile= 0;
  while (true) {
    File entry =  dir.openNextFile();
    //Serial.println(entry);
    if (! entry) {
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
    }
    //Serial.println(entry.name());
    countfile++;
    entry.close();
  }

  dir.close();
 String countString="";
 countfile++;
 if (countfile<100){countString+="0";}
 if (countfile<10){countString+="0";}
 countString+=String(countfile);
 countString+=".txt";
  
 Serial.println("****************");
 Serial.println(countString);
 return (countString);
}
    String filename=sdFilecount();

The function name IMPLIES that it returns a count of the files on the card. To me, that IMPLIES that it returns an int. It is pointless to store the int in a String instance.

Some renaming is clearly in order.

 File dataFile = SD.open(filename, FILE_WRITE);
 if (dataFile) {
   dataFile.println(dataString);
   dataFile.close();
   Serial.println("File Written");
 } 
 dataFile.close();

Close the file, even if you didn't succeed in opening it. Why?

What SD class are you using? I didn't think that SD.open() accepted a String.

    for (uint8_t i = 0; i < numTabs; i++) {
    }

Regardless of how many tabs there are, do nothing. Why is this crap even here?

 String countString="";
 countfile++;

You've already counted the files. Why are you lying about that by adding one to the count?

The code you posted does something, and generates some output. You have not been clear enough on what it actually does, nor have you shown any output.

You should first start by printing the name of each file counted. If the names are not correct, counting them is silly.

Dear PaulS and all

Thanks for your fast answer.
It looks that I was not clear with my question and explanation of the case. I’m sorry about that.
I will try again:-) and split my code with explinations

Idea of the Project.
I want to save some date after pushing a button. I do not want, that the new data are added to an existing file or overwrite an existing file. The idea is that is saves the data in consecutive numbered files.
Example: 001.txt, 002.txt, 003.txt and so on

Idea of my solution:
Before saving the data, my function sdFilecount() returns counts how many files exist on my SD card. Add 1 for the next to write file. Formats the counting into the format 000.txt and sends it back as a string.
The “counting string” is the file name that is send to the function writeonSD().

What happens executing the code:
Let’s assume they are already 7 files on the SD Card.
Bushing the Button the first time, it counts correct and saves a file with the filename 008.txt. This is what I accepted to do.

If I push the button a second time (without switching of the Arduino) the file counting does not work and a file 001.txt is saved instead of 009.txt.
This is the same for all following button push, till I switch the Arduino off and again on.

Used Library:
I use the “standard” SD-Card library that is included in the Arduino environment (I’m a newbie and was till now not into the library story)

I hope I was clearer this time:-)

Following the code with some additional coments

//Button 1
const int buttonPin1 =2;     // the number of the pushbutton pin
int buttonState1 = 0;         // variable for reading the pushbutton status

//SD Card
#include <SD.h>             // I use the "standard" library
const int chipSelect = 10;


void setup()
{
 Serial.begin(9600);

//Button 1
    pinMode(buttonPin1, INPUT); // initialize the pushbutton pin as an input:

//SD Card
   Serial.print("Initializing SD card...");
   pinMode(10, OUTPUT);
   // see if the card is present and can be initialized:
   if (!SD.begin(chipSelect)) {
     Serial.println("Card failed, or not present");
     return;
   }
   Serial.println("card initialized.");
}


void loop()
{
  //Button1
  buttonState1 = digitalRead(buttonPin1);
  // check if the pushbutton 1 is pressed.
  if (buttonState1 == 1){

    String filename=sdFilecount();             //function counts how many files exist on the SD card, add 1 and converts the nr of files into a String of the format "000.txt"

    writeonSD(filename);                //function saves a file on the SD card with the name "filename"
    } 
  delay (500); 
}
void writeonSD(String filename){

 String dataString="This is a Test";
 
 File dataFile = SD.open(filename, FILE_WRITE);
 if (dataFile) {
   dataFile.println(dataString);
   dataFile.close();
   Serial.println("File Written");
 }  
  
}
String sdFilecount( ) {
  File dir = SD.open("/");
  int numTabs=0;
  int countfile= 0;
  while (true) {
    File entry =  dir.openNextFile();
    //Serial.println(entry);
    if (! entry) {
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
    }
    Serial.println(entry.name()); //controll to see what he counts
    countfile++;
    entry.close();
  }

  dir.close();

//Convert counting in to filename format
 String countString="";
 countfile++;
 if (countfile<100){countString+="0";}
 if (countfile<10){countString+="0";}
 countString+=String(countfile);
 countString+=".txt";
  

 Serial.println("****************");   //for control
 Serial.println(countString);                //for control
 return (countString);
}

I'm not going to try to sew your code together, in the proper order, guessing about what isn't there.

Post it as ONE piece of code (ALL of it). If it is too big, post it as an attachment. ALL of this is explained in the sticky at the top of the forum.