gpt4 book ai didi

c - 如何从 C 程序读取 .txt 文件或 .csv 文件?

转载 作者:行者123 更新时间:2023-11-30 14:29:58 25 4
gpt4 key购买 nike

哪个C函数适合读操作?实际上我的 .txt 或 .csv 文件具有如下所示的固定模式:

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 程序中读取?

最佳答案

最简单(但也是最不灵活并且有一些陷阱的是使用 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 库。

编辑:已编辑问题的 readRecord 版本(每条记录位于单独的行上)。

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

关于c - 如何从 C 程序读取 .txt 文件或 .csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3994915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com