10 years, 1 month ago.

SD card reading data from a buffer

I need a little help with the code I took from another question I found on Mbed. This reads two values from the buffer all separated by ","

I need to change this and read four values (these will be mintemp, maxtemp, minhumid, maxhumid). Is it possible to modify the code below to read four values rather than two or would I need a different approach? My final buffer length may well be different, should I use 'sizeof' somewhere to set the correct buffer length?

Many thanks.

SD data logging

int main()
{

FILE * fp;
char Buffer[256];
char * pEnd;
float Temperature, Humidity;
 
    
    fp = fopen("/sd/log1.txt", "r");
    if(fp == NULL) { error("Could not open file for reading\r\n"); }
    
    while(fgets (Buffer, 256, fp) != NULL){
        Buffer[strlen(Buffer)-1] = 0;
        pc.printf("String = \"%s\" \r\n", Buffer);
        
        Temperature= strtof (Buffer, &pEnd);
        if(pEnd[0]==','){ pEnd[0]=' '; }
        Humidity = strtof (pEnd, NULL);
       

 
        }
    fclose(fp);
}

Thanks for the information David, I used the strtok function and this works as I need.

My working code

    fp = fopen("/sd/logs.txt", "r");
    if(fp == NULL) {SDmenu();}      
    fgets (buf, 100, fp);
    p = strtok (buf,",");log1time = atoi(p);
    p = strtok (NULL, ",");log1scale = atoi(p);
    p = strtok (NULL, ",");log2time = atoi(p);
    p = strtok (NULL, ",");log2scale = atoi(p);
    p = strtok (NULL, ",");log3time = atoi(p);
    p = strtok (NULL, ",");log3scale = atoi(p);
    p = strtok (NULL, ",");log4time = atoi(p);
    p = strtok (NULL, ",");log4scale = atoi(p);
    fclose (fp);  
         
    fp = fopen("/sd/maxmin.txt", "r");
    if(fp == NULL) {SDmenu();}      
    fgets (buf, 27, fp);
    p = strtok (buf,","); maxtemp = strtof (p, NULL);
    p = strtok (NULL, ","); mintemp = strtof (p, NULL);
    p = strtok (NULL, ","); maxhumid = strtof (p, NULL);
    p = strtok (NULL, ","); minhumid = strtof (p, NULL);
    fclose (fp);
  

1 Answer

10 years, 1 month ago.

Hi Paul,

You certainly could extend the example, and that should work. If your source is not always well formed, you may need some additional error checking. As an alternative, consider strtok( ), which may also be a potential solution.

Here's a few links showing examples:

Accepted Answer