【发布时间】:2013-02-06 12:24:09
【问题描述】:
我正在尝试做这里已经完成的事情 Read co-ordinates from a txt files using C Program 。我尝试输入的数据是这种格式:
f 10 20 21
f 8 15 11
. . . .
f 11 12 25
我的点结构的唯一区别是我有一个额外的字符来存储第一列中的字母(可能是也可能不是字母 f)。我想我要么声明我的字符错误,要么我在printf 中错误地调用它。无论哪种方式,我只读取第一行,然后我的程序终止。有什么想法吗?
下面是我的 MWE
#define FILEPATHtri "/pathto/grid1DT.txt"
#define FILEPATHorg "/pathto/grid1.txt"
#define MAX 4000
#include <stdio.h>
#include <stdlib.h>
#include "math.h"
typedef struct
{
float x;
float y;
float z;
char t[1];
}Point;
int main(void) {
Point *points = malloc( MAX * sizeof (Point) ) ;
FILE *fp ;
fp = fopen( FILEPATHtri,"r");
int i = 0;
while(fscanf(fp, "%s %f %f %f ", points[i].t, &points[i].x, &points[i].y, &points[i].z ) == 4 )
{
i++;
}
fclose(fp);
int n;
for (n=0; n<=i; n++){
printf("%c %2.5f %2.5f %2.5f \n", points[i].t, points[n].x, points[n].y, points[n].z ); }
printf("There are i = %i points in the file \n And I have read n = %i points ",i,n);
return 0;
}
【问题讨论】:
-
你为什么使用
char t[1]而不是简单的char t? -
似乎是熟悉调试器的绝佳时机,如果您使用的是基于 linux/unix/etc 的系统,我可以推荐 GDB!
-
@Fredrik : 我推荐 DDD
-
你应该检查 fp 是否有效。