I have been working on the following bit of code and am having trouble with my file handling operations.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
int lineCount=0;
char line[200];
char *lineArray[lineCount];
char *CityName[20];
double longitudinal[10];
double latitudinal[10];
int serialno[10];
char *token;
const char j=' ';
int x=0,p=0;
FILE *file;
file=fopen("chota.txt","r");
if(file==NULL)
{
printf("file is not opened properly\n");
return -1;
}
//below one to give total number of lines.
while ((fgets(line,sizeof(line),file)) != NULL)
{
lineCount++;
}
lineArray = (char *)malloc(sizeof(char *)*lineCount);
rewind(file);
printf("The total number of cities in the file is: %d\n",(lineCount-1));
fgets(line,sizeof(line),file);//moves file pointer to beg of 2nd line
while ((fgets(line,sizeof(line),file)) != NULL)
{
lineArray[p]=malloc(strlen(line));//1st bunch of memory allocated
strcpy(lineArray[p],line);
printf("%s\n",lineArray[p]);
token = strtok(lineArray[p],j);
//printf("%s\n",token);
serialno[p]=atoi(token);
printf("%d\n",serialno[p]);
x=1;
/* walk through other tokens */
while( token != NULL )
{
//printf( " %s\n", token );
if((x%4)==1)
{
//longitudinal[p] =malloc(strlen(token));
longitudinal[p] =atof(token);
}
else if((x%4)==2)
{
//latitudinal[p]=malloc(strlen(token));
latitudinal[p]=atof(token);
}
else if((x%4)==3)
{
CityName[p] = malloc(strlen(token));
strcpy(CityName[p],token);
printf("%s\n",CityName[p]);
}
token = strtok(NULL, j);
x++;
} //end of inner while
p++;
}//end of outer while
}//end of main
The file that I am using is:
City_No Latitude Longitude City_Name
1 12.58 77.38 Bangalore
2 14.18 74.55 JogFalls
3 15.09 76.55 Bellary
4 26.48 84.33 Bettiah
5 25.37 85.13 Patna
6 19.18 84.51 Berahampur
7 20.15 85.51 Bhuvneshwar
8 25.30 90.30 Shillong
The problem is that I have been trying this for the past few days and I keep getting errors. I am not getting anywhere with debugging and cannot figure out where I am going wrong.