(C)从文本文件读取到结构

时间:2013-12-07 17:42:59

标签: c struct scanf

我试图从文本文件中直接读取多个不同的数据类型(char,int,float)到一个Structure中。

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

这应该读出来(当它决定合作时)并将其保存到结构中:

 Angle_Lifeboat L Angle 51.685 -5.102 25.0 600 120
 Angle_ILB L Angle 51.685 -5.102 25.0 180 30
 Broad_Haven_ILB L Broad_Haven 51.713 -5.113 25.0 180 30

但是读了这个

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很陌生,所以对我很轻松。您可以给予任何帮助

编辑:结构 - &gt;

 typedef struct assets{
char name[25];
char type[1];
float longi;
float lati;
char location[20];
int speed;
int fuelTime;
int readyTime;
 } assets;

3 个答案:

答案 0 :(得分:0)

fread(&my_struct, sizeof(my_struct), 1, fp);

答案 1 :(得分:0)

在c编程中我确实认为已经有一个构建函数来执行上述操作... 尝试使用fread http://www.tutorialspoint.com/c_standard_library/c_function_fread.htm

答案 2 :(得分:0)

  • BLUEPIXY正确地注意到 != EOF不良位置;正确的是:

    … &assets[i].readyTime) != EOF) {
    
  • 我们无法将assets[i].type中的字符作为带%s的字符串打印,因为1-char-array type[1]没有(空间)终止空值字符;我们必须将其打印为带有 precision .1或字符的字符串:

    printf("…%.1s…\n", …assets[i].type…);   // need no & operator
    

    printf("…%c…\n", …*assets[i].type…);    // need * operator
    
  • 转化规范%lf用于指向double(而非float)的指针; float需要转化规范%f

  • 由于speed值为25.0,我们无法将其视为%d的整数;我们需要使用float读取%f变量,或者将临时变量分配给assets[i].speed,或者在float speed;中定义assets。< / p>