(C) 从文本文件读取到结构
我正在尝试将文本文件中的多种不同数据类型(char、int、float)直接读取到结构中(C) 从文本文件读取到结构,c,struct,scanf,C,Struct,Scanf,我正在尝试将文本文件中的多种不同数据类型(char、int、float)直接读取到结构中 readData() { char filename[100]; int linesread; int i = 0; printf("Enter the assets text file that you wish to read: \n"); scanf("%s", filename); if ((fp = fopen(filename, "r")) == NULL) { printf("Er
readData() {
char filename[100];
int linesread;
int i = 0;
printf("Enter the assets text file that you wish to read: \n");
scanf("%s", filename);
if ((fp = fopen(filename, "r")) == NULL) {
printf("Error opening data file\n");
readData();
} else {
while (fscanf(fp, "%s %c %s %lf %lf %d %d %d", &assets[i].name, &assets[i].type, &assets[i].location, &assets[i].longi, &assets[i].lati, &assets[i].speed, &assets[i].fuelTime, &assets[i].readyTime != EOF)) {
i++;
}
}
fclose(fp);
linesread = i;
for (i = 0; i < linesread; i++) {
printf("%s %s %s %lf %lf %d %d %d\n", &assets[i].name, &assets[i].type, &assets[i].location, &assets[i].longi, &assets[i].lati, &assets[i].speed, &assets[i].fuelTime, &assets[i].readyTime);
}
而是读到了这个
ngle_Lifeboat LAngle Angle 0.000000 0.000000 0.000000 4231936 4231940
Angle_ILB LAngle Angle 0.000000 0.000000 0.000000 4232008 4232012
Broad_Haven_ILB LBroad_Haven Broad_Haven 0.000000 0.000000 0.000000 4232080 4232084
我对C很陌生,所以对我放松点。如果您能提供任何帮助,我们将不胜感激
编辑:结构-->
在c编程中,我确实认为已经有一个内置函数来完成上面的工作。。。 尝试使用fread
- BLUEPIXY正确地注意到了
位置不良;正确答案是:!=EOF
… &assets[i].readyTime) != EOF) {
- 我们无法打印
资产[i]中的字符。请键入
作为字符串,因为1-char-array%s
没有终止空字符的空间;我们必须将其打印为精度为类型[1]
的字符串或字符:.1
或printf("…%.1s…\n", …assets[i].type…); // need no & operator
- 转换规范
用于指向%lf
(而不是double
)的指针;float
s需要转换规范float
%f
- 由于
值为速度
,因此我们无法将它们作为25.0
的整数读取;我们需要读取带有%d
的%f
变量,或者是一个临时变量,然后分配给float
,或者通过定义资产[i].speed
float speed代码>在
资产中
结构的声明!=EOF
糟糕的位置。编辑EOF的位置建议/思考不是此类问题的答案。任何帮助都非常好。”fread’看起来很有用,有人能给我一些正确使用它的建议吗
fread(&my_struct, sizeof(my_struct), 1, fp);
… &assets[i].readyTime) != EOF) {
printf("…%.1s…\n", …assets[i].type…); // need no & operator
printf("…%c…\n", …*assets[i].type…); // need * operator