How can I read specific data columns from a file in c

chriscol picture chriscol · Jul 28, 2010 · Viewed 14.5k times · Source

Good day all,

I am a beginner in c programming.I have this problem and have have spent quite a huge amount of time on it without any considerable progress.

My problem is stated thus:

I have a series of files with the extension (.msr), they contain measured numerical values of more that ten parameters which ranges from date,time,temperature, pressure, .... that are separated by semi colon. The examples of the data values are shown below.

2010-03-03 15:55:06; 8.01; 24.9; 14.52; 0.09; 84; 12.47;
2010-03-03 15:55:10; 31.81; 24.9; 14.51; 0.08; 82; 12.40;
2010-03-03 15:55:14; 45.19; 24.9; 14.52; 0.08; 86; 12.32;
2010-03-03 15:55:17; 63.09; 24.9; 14.51; 0.07; 84; 12.24;

Each of the files have as a name REG_2010-03-03,REG_2010-03-04,REG_2010-03-05,... and they are all contained in a single file.

  1. I want to extract from each of the file the date information which in this case 2010-03-03, column 3 and column 6.

  2. Find the statistical mean of the each of the columns of 3 and 6.

  3. Then store the results in a new file which will only contain the date,and the calculated mean of the columns above for further analysis.

They are to be written in c.

I am really counting or your assistance to this to get going on this.

Regards

Answer

Daniel Egeberg picture Daniel Egeberg · Jul 28, 2010

Here is a starting point:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    char str[] = "2010-03-03 15:55:06; 8.01; 24.9; 14.52; 0.09; 84; 12.47;";
    char *date, *tmp;
    double mean = 0;
    int i;

    date = strtok(str, " ");
    strtok(NULL, " "); // skip over time
    while (tmp = strtok(NULL, ";")) {
        ++i;
        if (i == 3 || i == 6) { // get only the 3rd and 6th value
            mean += strtod(tmp, NULL);
        }
    }
    mean /= 2;

    printf("%s: %.2f\n", date, mean);

    return 0;
}

You'll just have to do something like that to each line.