Problem using SD.remove() with Ethernet Shield & UDP Communication

Hi everyone!

I would appreciate if you could help me with one annoying problem I am not able to fix.

I am doing a program that allows me to storage in a text file the votes of an “noncontinuous” use of the program. With “noncontinuous” I mean that I aim to create a text file with the first vote given, updating this file with every new vote, and if I disconnect the Arduino and turn on it again, the program could read the file, and save the votes in an “int” variable to continue counting from the last voting. The votes could be given by pushing a switch, or while UDP communication through a mobile app.

Every time a vote is given, the text file is removed with the SD.remove() function, and then a new text file is created with the same name of the previous one, and the voting updated, to have a simpler data file with just one line to read.

Everything works OK the first time that the program runs if the text file does not exist from the beginning, but if the text file exist, I run the program for second time after disconnect the Arduino, and I open the serial monitor to watch the print data, the program does not capable to use the SD.remove() function. If I do not open the Serial Monitor, everything continues going perfect, but it is not useful. I do not know if there is a problem with the Serial, but for me it has non sense, so I would really appreciate your help if you know what could be the problem.

I am using is an Arduino Mega 2560 and an Ethernet Shield.

Here I write you the part that the second running is “ignored”:

switch (fase)
  {
    case 1:
            
          voto = voto + 1; 

          if (SD.exists("votos.txt"))
          {
            Serial.println("EXISTE");
            SD.remove("votos.txt");
            delay(100);
            
          }

          if(!SD.exists("votos.txt"))
            {          
              Serial.println("Archivo eliminado");
            }

And also I attach you the whole code used,

Thanks

Votos.ino (7.03 KB)

Every time a vote is given, the text file is removed with the SD.remove() function, and then a new text file is created with the same name of the previous one, and the voting updated, to have a simpler data file with just one line to read.

I do not understand this. Open the file. Read the data. Convert the data to a value. Close the file. Update the value. Open the file. Write to the file. Close the file. No reason to remove the file.

Hi Paul, thanks for your answer!

I want to remove the data file every time because I just want one line on the data file to read and have an ease read of the data number. I do not want one line for each time that the program writes, with different data number. I just need the last voting.

If you open the file for writing with the truncate attribute set, writing one line will result in one line in the file when you close it.