开发者

How to read a .txt file or a .csv file from C program? [closed]

开发者 https://www.devze.com 2023-01-21 16:40 出处:网络
Closed. This question needs to be more focused. It is not currently accepting answers. 开发者_运维问答Want to improve this question? Update the question so it focuses on one problem only b
Closed. This question needs to be more focused. It is not currently accepting answers.
开发者_运维问答

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 4 years ago.

Improve this question

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?


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

精彩评论

暂无评论...
验证码 换一张
取 消