-1

这就是我到目前为止所拥有的。我需要读取文件day.txt,计算文件的行数

#include "stdio.h"
#include "stdlib.h" 

#define MAX_LINE_LENGTH 

struct earthquake_t{ 
    float lat;
float lng;
float dep;
float mag;
};
FILE* fid;
int main(void)
{
double lat,lng dep,mag;
double userminlat,userminlng,usermaxlat,usermaxlng,minlat,minlng,maxlat,maxlng,i, ch,line;
struct earthquake_t *earthquake;

fid=fopen("day.txt","r");

while (!feof(fid))
{        /*Need help counting lines*/
    count = fscanf(fid," %lf %lf %lf\n",&lng,&lat,&dep,&mag);
/* count tell you how many of the % fields were matched,
 and you need to make sure all three were found to avoid blank lines*/

    if (count ==3)
    {
        line ++;
    }
}

fseek(fid,1,SEEK_SET);
print("%d\n",sizeof(struct earthquake_t));        
earthquake = (struct earthquake_t *)malloc(sizeof(struct earthquake_t)*line);

for (i=0;i<line;i++)
{        
    fscanf("fid,%lf %lf %lf\n",&lng,&lati,&elevi)
    earthquake[i].lat=lat;
    earthquake[i].lng=lng;
    earthquake[i].dep=dep;
    earthquake[i].mag=mag;


    /*Setting the min and max values for latitude and longatidue*/
    if(earthquake[i].lng >maxlng) 
    {     
        maxlng = earthquake[i].lng;
    }
    if(earthquake[i].lng >minlng)
    {    
        minlng = earthquake[i].lng;
    }
    if(earthquake[i].lat >maxlat)
    {
        maxlat = earthquake[i].lat;
    }
    if(earthquake[i].lat >minlat)
    {
        minlat = earthquake[i].lat;
    }

}
4

1 回答 1

0

I would use fgets() to get a whole line from the text file and put it into a string and use sscanf() to extract your values.

/* count tell you how many of the % fields were matched,
and you need to make sure all three were found to avoid blank lines*/

The scanf man page states in part:

Return Value

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.

You could check for line[0] == '\n' to avoid blank lines.

Hope that helps.

于 2013-03-22T03:13:18.103 回答