如何阅读txt文件,或从C程序.csv文件? [英] How to read a .txt file or a .csv file from C program?
问题描述
谁能帮助我,指导我如何读一个.txt文件或从C程序.csv文件。
我的意思是它的C函数适用于读取操作?其实我的.txt或.csv文件如下所示的固定模式:
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
另外的文件.txt或.csv很容易从C程序来读取?
Further which file .txt or .csv is easy to read from C program?
推荐答案
最简单的(也是最不灵活,并与一些陷阱是使用scanf函数):
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);
对于任何高级的应用(读比快速和肮脏的解决方案更多的东西),我建议使用一些散落各地的互联网CSV库。
For any advanced use (read anything more than quick and dirty solutions) I recommend to use some of csv libraries scattered around internet.
编辑:readRecord版本的编辑问题(在单独的行每条记录)。
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;
}
}
这篇关于如何阅读txt文件,或从C程序.csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!