Problems deleting files from an SD card.

G'day all-

I've been working on a project where the basic idea is that it tracks a number of "passes" for multiple people, and saves them on an SD card. However, I've found that when I try and delete the file so that I can rewrite it with a new number, nothing happens. I get no compiler errors, but it simply doesn't work. This is my script:

void addPass()
{
  char fileStr[7]; //Define arrays for reading from SD
  char result[7];
  int i=1;
  currentFile = SD.open(openFileByNumber("passes"), FILE_READ); //open file
  while(currentFile.available())
  {
    fileStr[i] = currentFile.read(); //Read data onto SD
    i++;
  }
  i=1;
  currentFile.close();
  Serial.print(openFileByNumber("passes"));
  Serial.print(SD.remove(openFileByNumber("passes"))); //Remove file on SD
  
  while(fileStr[i] != '\0' && i < sizeof(result) - 1) //Convert array to long
  {
    result[i] = fileStr[i];
    i++;
  }
  result[i] = '\0';
  long currentPasses = atol(result);
  Serial.print(currentPasses);
  
  currentFile = SD.open(openFileByNumber("passes"), FILE_WRITE); //new file
  currentPasses++; //up passes
  currentFile.write(currentPasses); //save new number
}

Yes, I know this code is awful and messy :stuck_out_tongue:

I've done some testing and found that if I specify the name of the file in quotes "exampleFolder/example.txt" it works fine, but not when I use my file determining function:

char* openFileByNumber(String fileName)
{
  String tempString = String(name);
  char fileToOpen[15];
  char tempArray[10];
  tempString.toCharArray(fileToOpen,15);
  fileName.toCharArray(tempArray, 10);
  strcat(fileToOpen, "/");
  strcat(fileToOpen, tempArray);
  strcat(fileToOpen, ".txt");
  return(fileToOpen);
}

Note: I'm using the default SD library. Also, to clear any confusion, the reason I have to use this function is because, A: The Arduino SD Liberary takes character arrays, not strings, as input, and B: My file system stores each persons name and total in a folder with a number, so the program has to treat it as such.

I've been stuck on this problem for a while and I have no clue where to go from here. If anyone has any suggestions, please let me know. I'll try and clear up any questions you might have, because I know this probably doesn't explain everything. Thanks in advance!

-Spaceminer_

  return(fileToOpen);

Returning a pointer to memory that is going out of scope is a bad idea. A REALLY bad idea.

Forget that the String class exists. Learn to deal with C strings - NULL terminated arrays of chars.