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

Good afternoon,

I am starting to program in c. I have this problem, and I spent a lot of time on it without any significant progress.

My problem is formulated as follows:

I have a series of files with the extension (.msr), they contain measured numerical values ​​of more than ten parameters, which vary from date, time, temperature, pressure, .... which are separated by a semicolon. The following are examples of data values.

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 has the name REG_2010-03-03, REG_2010-03-04, REG_2010-03-05, ... and all of them are contained in one file.

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

  • Find the statistical average of each column from 3 and 6.

  • , .

c.

, .

+3
2

:

#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;
}

- .

+2

sscanf . sscanf , .

/* sscanf example */
#include <stdio.h>

int main ()
{
  char sentence []="Rudolph is 12 years old";
  char str [20];
  int i;

  sscanf (sentence,"%s %*s %d",str,&i);
  printf ("%s -> %d\n",str,i);

  return 0;
}

Rudolph -> 12

, , , SO.

:

, , strtok strtok_r ( strtok). , .

0

Source: https://habr.com/ru/post/1756909/


All Articles