delete contents of a text file in SD card

hi all :wink:
I need just to delete only contents of a text file in sd card.
Is there anyone who can help me to solve this problem ?? thank you :wink:

sarrah:
I need just to delete only contents of a text file in sd card.
Is there anyone who can help me to solve this problem ?? thank you :wink:

Just the contents, but keep the file and even the file size?

Perhaps: Open file, set file position to beginning of file, overwrite all existing contents with space characters, close file?

Which of these steps is the problem you need help with?

Just the contents, but keep the file that's what I need.
I need to get an empty file.
Do you think that overwriting all existing contents with space characters is a good idea?

sarrah:
Just the contents, but keep the file that's what I need.
I need to get an empty file.
Do you think that overwriting all existing contents with space characters is a good idea?

ASCII-32 (space character) is always a good idea to create empty places in text files.

If you overwrite all bytes in the file with ASCII-32, the whole file will contain one long line of space characters. One line of empty space text only.

If you also want to keep all existing line breaks in the existing file, you'd have to read and write if this programming logic:

  • read one char from file:
  • if it is ASCII-13 or ASCII-10 ==> do nothing
  • otherwise write back space character (ASCII-32) in place

In that case, all existing line breaks in the text file will remain where they had been in the original text file, but all contents is replaced by space characters. So the number and length of lines will stay the same.

If you just want to create an empty 0-byte file, it's easier: Open the file, seek file position 0, truncate the file and close the file. That way you get a file with 0 bytes and absolutely no contents in it.

Going to ask the obvious stupid question.... why not place it in a computer and do it manually?

what I need is to delete the file contents when the Arduino is installed in the box. I have to communicate between Arduino and PC with serial port and do what I want in the file, but not manually

jurs:
ASCII-32 (space character) is always a good idea to create empty places in text files.

Based on sarrah's description

sarrah:
I need to get an empty file.

I don't think this is about "empty places", it seems the goal is having a "whatever.txt" filled with something and getting an empty "whatever.txt" afterwards. So I don't see why you would put spaces (or anything else) in it instead of just deleting and recreating the file.

remove() and open() (also see http://arduino.cc/en/pmwiki.php?n=Reference/SD) should do the trick.

i dont think deleting and recreating the file will be good because I have many files and each time I select one file

sarrah:
i dont think deleting and recreating the file will be good because I have many files and each time I select one file

Each time you select one file... something happens? Sorry, I don't really understand that sentence.

Do you mean opening multiple files at a time? That should work:

As of version 1.0, the library supports opening multiple files.

And even if it doesn't or gives you any problem, you could just close file A you're accessing, delete and recreate file B and open file A again.

I don't see the problem here - what exactly are your concerns with this?

jurs:
If you just want to create an empty 0-byte file, it's easier: Open the file, seek file position 0, truncate the file and close the file. That way you get a file with 0 bytes and absolutely no contents in it.

The thing is: How would you truncate it? I can't find a method in the SD library to do so. (EDIT: At least not in Arduino's "official" SD library)

well, files are selected based on binary combination. for example, if I need the third file I sent 011. and this is selected as needed from the operator.

sarrah:
well, files are selected based on binary combination. for example, if I need the third file I sent 011. and this is selected as needed from the operator.

What does the one thing have to do with the other? How does that stop you from deleting and recreating a file? Because you don't know which one?

If you truncate the contents of a file or if you delete and recreate it: In both cases you need to access the file.

So I assume(!) you're saying: "While I have a file opened and some condition applies, I want to delete its contents right at this moment". So just close it, remove it, recreate it. If you need to write anything to it again, just instantly reopen the now empty file.

As said: You have not given a comprehensible reason why this wouldn't work.

I just took a closer look at the SD library:

There is actually a way of truncating files, but it's probably not like you want it to - for some reason this is not documented in the Arduino reference, see here. The parameter would be just O_TRUNC or O_CREAT | O_TRUNC | O_WRITE, I'm not sure and not able to test this right now.

However those are parameters for the open()-method, so for using that you need to open the file in that mode as well, so it probably won't solve your problem. Except I misunderstood you and what you actually want to do is overwrite a file when opening and before writing, that's exactly what this parameter would do.

BTW:

Also have a look at this, it's pretty much your question with pretty much my answer.

If that doesn't help, please provide some code that shows your problem.

void loop() 
{   
  if (!SD.begin(4))  
   { 
     Serial.println("initialization SD card failed");
   }
   else
   {
     //Selection et ouverture du fichier// 
     b0= digitalRead(broche5); //Lire la sortie de la broche 5//
     b1= digitalRead(broche6); //Lire la sortie de la broche 6//  
     b2= digitalRead(broche7); //Lire la sortie de la broche 7//  
     b3= digitalRead(broche8); //Lire la sortie de la broche 8//
     
     if(b0==1 && b1==0 && b2==0 && b3==0)
      {
         myFile= SD.open("CMD26.txt",FILE_READ);
      }   
     else if(b0==0 && b1==1 && b2==0 && b3==0)
      {    
      myFile= SD.open("fichier2.txt",FILE_READ);
      }   
     else if(b0==1 && b1==1 && b2==0 && b3==0)
      {    
      myFile= SD.open("fichier3.txt",FILE_READ);
      }       
     else if(b0==0 && b1==0 && b2==1 && b3==0)
      {    
      myFile= SD.open("fichier4.txt",FILE_READ);
      }   
     else if(b0==1 && b1==0 && b2==1 && b3==0)
      {    
      myFile= SD.open("fichier5.txt",FILE_READ);
      }   
     else if(b0==0 && b1==1 && b2==1 && b3==0)
      {    
      myFile= SD.open("fichier6.txt",FILE_READ);
      }       
     else if(b0==1 && b1==1 && b2==1 && b3==0)
      {    
      myFile= SD.open("fichier7.txt",FILE_READ);
      }   
     else if(b0==0 && b1==0 && b2==1 && b3==0)
      {    
      myFile= SD.open("fichier8.txt",FILE_READ);
      }       
     else if(b0==1 && b1==0 && b2==0 && b3==1)
      {    
      myFile= SD.open("fichier9.txt",FILE_READ);
      }
      else 
      {
       Serial.println("error opening file");
      }
   }
    while (myFile) //Tant que le fichier est ouvert//
    {
      buttonInt1=digitalRead(buttonPin1);
      if(buttonInt1==HIGH) //mode1=communication with machine//
       { 
        if (reponse==true) //Si la commande précédente est envoyée et la réponse correcte est réçue on envoi la commande suivante//
        {      
        //Lecture de la commande//
          do 
          { 
            if(c=='&') //Si toutes les commandes sont envoyées avec succés et les réponses correctes sont réçues on allume la led verte// 
            {
             digitalWrite(led_verte, HIGH);
            }
            else //Lire la commande//
            {        
            c = myFile.read();
            commande += c;
            }
          }
          while (c != '\n');
         
          // Envoie de la commande//
          Serial.println(commande);
          
          // Lecture de la réponse attendue//
          do 
          {
            c = myFile.read();
            reponseattendue += c;
          }
          while (c != '\n'); 
          
          //Elimination du "#" (premier caractère dans la réponse attendue qui sert à différencier entre la commande et la réponse)//         
          L=reponseattendue.length();
          reponseattendue=reponseattendue.substring(1,L-2);            
          
          // Réception de la réponse//
          unsigned long Timeout;
          Timeout =millis(); // Timer pour la gestion du timeout//      
          in = 0; // Initialisation de in//
          do 
          if(millis() - Timeout > 5000) //Si la réponse n'est pas reçue avant 5s on allume la led rouge//
           {
            digitalWrite(led_rouge, HIGH); 
           }
          else //Lire la réponse reçue//
          {        
            if (Serial.available() > 0) 
            {
              in = Serial.read(); 
              reponserecue += in;
            }
          } 
         while ( in != '\n' ); 
               
          // Passage des réponses attendues et reçues en LowerCase (pour ingnorer les différence minuscule/majuscule)//
          reponseattendue.toLowerCase();
          reponserecue.toLowerCase();
                          
          // Comparaison des résultats//
          if (reponserecue.indexOf(reponseattendue)<0 || reponserecue.indexOf("!")>=0) //Si la reponse réçue ne contient pas la réponse attendue ou contient un point d'exclamation On allume la led rouge//  
          {
            reponse=false;       
            digitalWrite(led_rouge, HIGH);
    
    
          }       
          // Remise à zero de tous les paramètres//
          reponseattendue = "";
          commande = "";
          reponserecue = "";      
        }    
    }
    else if(buttonInt1==LOW) //mode2=communication with  pc//
    {
  //here I will delete the contents of the selected file and write new lines//
      
    } 
  }
}

 //Une fonction qui redémarre le programme depuis le début//
  void reset(void) 
    {
     wdt_enable(WDTO_15MS);
     for(;;);
    }

OK, I see. As I can't find a method for getting the filename back from a File object, quick & dirty:

Declare two global variables (before calling loop()):

String filename;
char filenameCA[13];

In your if-else-blocks (those that check b0 to b3) you assign the filenames to filename, something like:

if(b0==1 && b1==0 && b2==0 && b3==0)
{
    filename="CMD26.txt";
}   

else if(b0==0 && b1==1 && b2==0 && b3==0)
{   
    filename="fichier2.txt";
}

and so on.

Instead of calling SD.open() in every case, you just call it once after you determined the filename:

filename.toCharArray(filenameCA, 13);
myFile= SD.open(filenameCA,FILE_READ);

The "delete" part would look like this:

myFile.close();
SD.remove(filenameCA);
myFile = SD.open(filenameCA,FILE_WRITE);

Now your file is empty and opened for writing again.

BTW: As you said "serial port", just to be safe: You are aware that RS232's voltages are higher and you can't just go directly into the Arduino's pins with that, right?

And I don't really get why you are even writing and reading an SD card, as the data doesn't seem to really need persistence anway.

hi, I have a similar problem
i'm working with an arduino nano and have a file on the sd card, I want to empty the file (not with spaces but really empty) without deleting the file
I've already read your answers but still don't understand how i can do this...

You need to re-read the answers, particularly JURS',, the last paragraph/sentence: "If you just want to create an empty 0-byte file, it's easier: Open the file, seek file position 0, truncate the file and close the file. That way you get a file with 0 bytes and absolutely no contents in it."