SD card - Moving specific records from File A to File B

I have created a file called ACTUAL.CSV which is record of certain operations. Once the operation is carried out the corresponding record in the file is updated with the operation details at the end and in the front a token '&'is changed to '%'. See the sample below :

<%1  ,A02B94FF  ,12 ,VrP Part9       ,101,6670    ,Drive shaft DE      ,ShellGadus3        , 16.2,05/19/16-16:07, >
<&2  ,604E95FF  ,10 ,VrP Part9       ,102,6670    ,Drive shaft NDE     ,ShellGadus3                               >
<&3  ,2C63B0F8  ,20 ,VrP Part9       ,103,Cold 1  ,CldPrWshCon1TailDE  ,ShellGadus3                               >
<&4  ,70E691FF  ,15 ,VrP Part9       ,104,Cold 1  ,CldPrWshCon1TailNDE ,ShellGadus3                               >

SO at the end of the day I need to pull out all records with a '%'token and create a fresh file called PENDING.CSV.

Created a code for that. It compiles OK but does not print as expected. Is there any basic approach issue in my logic ?

// FUNCTION TO CREATE THE PENDING FILE FROM ACTUAL FILE.CSV

void createPendingSummary() {

  char letter;
  String readString;
  unsigned int nextSDC_Index = 0;

  getNoOfRecords();                                        // First find the total number of records

  for ( int count = 0; count < noOfRecords + 1; count++) {

    File dataFile = SD.open("ACTUAL.CSV", FILE_READ);    // Open the existing Actual File
    dataFile.seek(nextSDC_Index);                        // Point to the start of the record to be read..
    char letter = dataFile.read();
    if ( letter == '<') {                                // Locate the record start
      statusToken = dataFile.read();                     // Acquire the token..
      dataFile.seek(dataFile.position() - 2);            // Move the sdcIndex back to start...to read full row..
    }
    if ( statusToken == '&') {                           // Is the record unfinished ??
      while ( dataFile.available()) {                    // If so read the record row into a String...
        letter = dataFile.read();
        if (letter == '>') {
          nextSDC_Index = dataFile.position();           // Save end of row for reading next record...
          dataFile.close();
          File pendFile = SD.open( "PENDING.CSV", FILE_WRITE) ;
          pendFile.print( readString) ;
          pendFile.println('>');
          pendFile.close();                              // Write the record + > into the Pendfile
          break;
        }
        else {
          readString += letter;
        }
      }// while(dataFile.available()
    }// statusToken =='&'
  } // for loop end

  File pendFile = SD.open( "PENDING.CSV", FILE_READ) ;
  while (pendFile.available()) {                           // Data file exists ..read it.
    SerialPort.write(pendFile.read());
  }
  pendFile.close();
} // Function end

NB : SerialPort refers to Serial in this case.

  String readString;

Ugh. That is NOT necessary. All your records are fixed length. Count how long one record is and create a char array of that size (plus one for the NULL). Use the overloaded file.read() method that takes an array. Read a complete record in one call. If the 2nd character is a %, write the complete record to the other file.

  for ( int count = 0; count < noOfRecords + 1; count++) {

As opposed to the more reasonable

  for ( int count = 0; count <= noOfRecords; count++) {

?

If there are 12 records, why do you want to read all 13 of them?

It compiles OK but does not print as expected.

It does something that you didn't explain. You have some expectations that you have not explained (though we can probably make a reasonable guess as to what you expect).

I agree Paul with all you said.

But I have one argument ( if I can call it that ) for the readString. Today each of the record is say X characters long. But there may be a change to the data as warranted by the client and at that time I need to change the number again. Instead if I look for an end marker ( '>') as in this case , I don't have to worry about the record length.

And of course as you pointed out I am reading all the records and choosing only that which has a token of '%' Your suggestion is good towards optimization of code.

I have used a break in the code - what I expect is to break the while loop to prevent reading all records in the SD card. Is that place OK ?

A<=B is a lot neat than A<B+1 !!

I don't have to worry about the record length.

Try making the record length 1000, and see if you have to worry about it. The String class is making Swiss cheese of your memory.

what I expect is to break the while loop to prevent reading all records in the SD card.

That isn't what the break does. It simply breaks of of the while loop that is reading data, causing the for loop to iterate again, which resumes reading the next record.

A<=B is a lot neat than A<B+1 !!

But it's still wrong. You want to read records 0 to n-1, of the n records.

Ok removed the readString and used a char array. Yet status remains same... no error... PENDING.CSV not created....

// FUNCTION TO CREATE THE PENDING FILE FROM ACTUAL FILE.CSV

void createPendingSummary() {

  char letter;
  char singleRecord[100];
  unsigned int nextSDC_Index = 0;

  getNoOfRecords();                                        // First find the total number of records

  for ( int count = 0; count < noOfRecords + 1; count++) {

    File dataFile = SD.open("ACTUAL.CSV", FILE_READ);    // Open the existing Actual File
    dataFile.seek(nextSDC_Index);                        // Point to the start of the record to be read..
    char letter = dataFile.read();
    if ( letter == '<') {                                // Locate the record start
      statusToken = dataFile.read();                     // Acquire the token..
      dataFile.seek(dataFile.position() - 2);            // Move the sdcIndex back to start...to read full row..
    }
    if ( statusToken == '&') {                           // Is the record unfinished ??
      for ( int count1 = 0; count1 < 100; count1++) {
        letter = dataFile.read();
        if (letter == '>') {
          nextSDC_Index = dataFile.position();           // Save end of row for reading next record...
          dataFile.close();
          File pendFile = SD.open( "PENDING.CSV", FILE_WRITE) ;
          pendFile.print( singleRecord) ;
          pendFile.println('>');
          pendFile.close();                              // Write the record + > into the Pendfile
          break;
        }
        else {
          singleRecord[count1] += letter;
          SerialPort.println(letter);
        }
      } // count1 loop
    }// statusToken =='&'
  } // for loop end

  File pendFile = SD.open( "PENDING.CSV", FILE_READ) ;
  while (pendFile.available()) {                           // Data file exists ..read it.
    SerialPort.write(pendFile.read());
  }
  pendFile.close();
} // Function end
        letter = dataFile.read();

I can't see what you read. Can you?

PaulS:

        letter = dataFile.read();

I can't see what you read. Can you?

Thanks. I think I see the bug : after the first iteration of the for loop, there is nothing which can be read. I did this because I thought for SD card operations only one file must be open at a time ?

Or can I leave the source file ACTUAL.CSV without closing it within the for loop ?

Each file that is open needs a 512 byte buffer. If you have the memory, have both files open.

But, the real question is are you reading what you think you are?

PaulS:
Each file that is open needs a 512 byte buffer. If you have the memory, have both files open.

But, the real question is are you reading what you think you are?

I am sorry ... it a bit difficult for me to answer that question. In the meanwhile I tried a simple method to extract the required row from the ACTUAL.CSV file and print to Serial port .

// The code is now compiled for just printing to Serial. Same to be  converted
// to write to PENDING.CSV file

void createPendingSummary() {
  char statusToken = '0';
  int data;
  File dataFile = SD.open("ACTUAL.CSV", FILE_READ);    // Open the existing Actual File
  //File pendFile = SD.open("PENDING.CSV", FILE_WRITE);

  while ((data = dataFile.read()) >= 0)  {
    if ( data == '<') {
      statusToken = dataFile.read();                    // Read the criteria to select the record
    }
    if (statusToken == '&') {                           // Read the record as criteria matches
      Serial.write('<');
      do {
        data = dataFile.read();
        Serial.write(data);
      } while ( data != '>');
      Serial.println();
      statusToken = '0';
    }
    if ( statusToken == '#') {                          // Ignore the record but simply loop thorugh the position
      do {
        data = dataFile.read();
      } while ( data != '>');
      statusToken = '0';
    }
  }
  //pendFile.close();                                    // Write the PENDING.CSV
  dataFile.close();
}

The above function is doing its job OK as can be seen from the Serial dump below :

<2  ,604E95FF  ,10 ,VrP Part9       ,102,6670    ,Drive shaft NDE     ,ShellGadus3        >
<4  ,70E691FF  ,15 ,VrP Part9       ,104,Cold 1  ,CldPrWshCon1TailNDE ,ShellGadus3        >
<6  ,2C52B0F8  ,5  ,VrP Part9       ,103,Cold 2  ,CldPrWshCon2TailNDE ,ShellGadus3        >
<8  ,D0FC97FF  ,8  ,VrP Part12      ,105,2.02    ,BtmWireGuideRollTS  ,MA6040-150-1.5     >
<10 ,70E891FF  ,20 ,VP3 Part11      ,104,2.04    ,BtmWireBreastRollTS ,MA6040-150-1.5     >

But when I try to convert the same code required for writing to PENDING.CSV as below, nothing happens. So whats wrong ?

// FUNCTION TO CREATE THE PENDING FILE FROM ACTUAL FILE.CSV

void createPendingSummary() {

  char statusToken = '0';
  int data;
  File dataFile = SD.open("ACTUAL.CSV", FILE_READ);    // Open the existing Actual File
  File pendFile = SD.open("PENDING.CSV", FILE_WRITE);  // Open the file to write the selected records..

  while ((data = dataFile.read()) >= 0)  {

    if ( data == '<') {
      statusToken = dataFile.read();
    }
    
    if (statusToken == '&') {
      pendFile.write('<');
      do {
        data = dataFile.read();
        pendFile.write(data);                        // Criteria token matches. Write the record to file..
      } while ( data != '>');
      statusToken = '0';
    }

    if ( statusToken == '#') {
      do {
        data = dataFile.read();                     // Ignore record. But move the read pointer for next
      } while ( data != '>');
      statusToken = '0';
    }
  }
  pendFile.close();                                 // Write the data and close file. 
  dataFile.close();
} // Function end

it a bit difficult for me to answer that question.

Why? Print the character you read from the file. Is it what you expect? It's an incredibly simple question.

But when I try to convert the same code required for writing to PENDING.CSV as below, nothing happens. So whats wrong ?

Each open file requires a 512 byte buffer. Do you have enough memory to have two files open at the same time?

Ok the final code in my previous post worked . Only it was taking a few seconds for the Write to complete and read back the file. I had in the meanwhile decided that the code is not doing anything ! This is the functionality I wanted.

Just one basic doubt : I have read that the data to SD card actually gets written only when its closed. Is there any criteria to the amount of data I can so accumulate before I close the file ?? So till the time it is put on the SD card where is it held - in the RAM ?

Thanks Paul for you patient guiding... this is the PENDING.CSV read dump

Initializing SD card...
SD Card initialized.
SerialToSD program ready 
Got the command !
PENDING.CSV Erased !!
<2  ,604E95FF  ,10 ,VrP Part9       ,102,6670    ,Drive shaft NDE     ,ShellGadus3        >
<4  ,70E691FF  ,15 ,VrP Part9       ,104,Cold 1  ,CldPrWshCon1TailNDE ,ShellGadus3        >
<6  ,2C52B0F8  ,5  ,VrP Part9       ,103,Cold 2  ,CldPrWshCon2TailNDE ,ShellGadus3        >
<8  ,D0FC97FF  ,8  ,VrP Part12      ,105,2.02    ,BtmWireGuideRollTS  ,MA6040-150-1.5     >
<10 ,70E891FF  ,20 ,VP3 Part11      ,104,2.04    ,BtmWireBreastRollTS ,MA6040-150-1.5     >

I have read that the data to SD card actually gets written only when its closed.

Data is committed to the card when the buffer gets full or when the flush() method is used to force the transfer. The close() method calls the flush() method.

Is there any criteria to the amount of data I can so accumulate before I close the file ?

One (512-byte) buffer full, minus one byte.

So till the time it is put on the SD card where is it held - in the RAM ?

Yes.