5 years, 7 months ago.

Reading data from a .csv file in SD card and storing that data into variables.

I have a .csv file with one row of comma separated data in SD card. I want to read it and store each comma separated value into different arrays or integers or floats variables. I am able to read one character or string using getc and gets. Now how to segment the full row using comma and store them separately. I am attaching a piece of code for reading one data value till comma. PFA.

FILE *stateLogFile2 = fopen("/sd/StateLog.csv","r");
    if (stateLogFile2!= NULL) {
        string a = "";
        string::size_type sz;
        char temp = fgetc(stateLogFile2);
        if(temp != ',' && temp != '\n'){   
            a+=temp;
        }
        else if(temp == ',' || temp == '\n'){
            int j = stoi(a, &sz);
            break;
        }
        fclose(stateLogFile2);
    }
    else {
        pcptr->printf("Read from StateLogFile failed!\n");
    }

2 Answers

5 years, 7 months ago.

Ideally you would read the whole row at once using gets() and then tokenize it. Take a look at the strtok() function - string to token. It will split a string based on a delimiter. It effectively breaks your single line string into a bunch of small strings. Each time you call it, it returns a pointer to the next token.

To use strtok() of course your data can't contain the delimiter. Maybe something like this:

#include <string.h> 
  
int main() 
{ 
    char buffer[] = "1, 2, 3, cat, sank"; 
  
    // first token 
    char* token = strtok(buffer, ","); 
  
    while (token != NULL) { 
        printf("%s\n", token); 
        token = strtok(NULL, ","); 
    } 
} 

5 years, 7 months ago.

To expand on Grahams answer:

#define _MAXLINELEN_ 64
FILE *stateLogFile2 = fopen("/sd/StateLog.csv","r");
char lineIn[_MAXLINELEN_];
if (stateLogFile2!= NULL) {
  while (!feof(stateLogFile2)) { // until the end of the file
    if( fgets (lineIn, _MAXLINELEN_, stateLogFile2 )) { // read one line
       char* token = strtok(lineIn, ",");    // split the line on ,
       while (token != NULL) {   // while there are entries left in the line
          // token is a pointer to a null terminated string of each value in turn
          printf("%s\n", token); 
          token = strtok(NULL, ","); 
      } // end while token,
   } // end if read a line
 }  // end while not end of file
} // end if opened file