tags:

views:

66

answers:

1

Could anyone help me by guiding me as how to read a .txt file or a .csv file from C program. I mean which C function is suitable for reading operation? Actually my .txt or .csv file has a fixed pattern shown below:

Temperature = 35
Pressure Segment 1
Slope = 5.5
Offset = 10

Temperature = 100
Pressure Segment 1
Slope = 53
Offset = 12

Temperature = 150
Pressure Segment 1
Slope = 1
Offset = 12

Further which file .txt or .csv is easy to read from C program?

+1  A: 

Simplest (but also least flexible and with some pitfalls is to use scanf):

#include <stdio.h>

struct Record {
  int temperature;
  unsigned int pressure_segment;
  double slope;
  int offset;
};

int readRecord(FILE* f, Record* rec) {
  if (fscanf(f, 
             "Temperature = %i Pressure Segment %u Slope = %lf Offset = %i\n", 
             &rec->temperature, 
             &rec->pressure_segment, 
             &rec->slope, 
             &rec->offset) == 4) {
      return 0;
  } else {
    return -1;
  }

}

Record rec;
FILE* f = fopen("your-file-name", "r");
while (!feof(f)) {
  if (readRecord(f, &rec) == 0) {
    printf("record: t: %i p: %u s: %lf o: %u\n", 
           rec.temperature, 
           rec.pressure_segment, 
           rec.slope, 
           rec.offset);
  }
}
fclose(f);

For any advanced use (read anything more than quick and dirty solutions) I recommend to use some of csv libraries scattered around internet.

EDIT: Version of readRecord for edited question (each record on a separate line).

int readRecord(FILE* f, Record* rec) {
  if (fscanf(f, 
    "Temperature = %i\nPressure Segment %u\nSlope = %lf\nOffset = %i\n", 
    &rec->temperature, 
    &rec->pressure_segment, 
    &rec->slope, 
    &rec->offset) == 4) {
      return 0;
  } else {
    return -1;
  }
}
MaR
Note that when the question was viewed for editing, the data seemed to be split over four lines - when this answer was given, the data seemed to be on one line for each set of 4 rows now on display.
Jonathan Leffler
@Jonathan: Thanks, "edit" version is out.
MaR