Hey,
I have a program that it supposed to read two columns of data and then perform a calculation on them. The problem is reading the data in from the file. I have a function to count the lines, this works correctly. It returns it's value into a variable called lines.
The program then tries to read data from the file into some dynamically allocated memory. It then prints the results.
However sometimes the data read from the file is absolute junk.
The thing is that the data is never junk if i don't call the function "countlines" and just assign the variable lines the length of the dat file.
WIERD
#include <stdio.h>
#include <stdlib.h>
int countlines(FILE* fp)
{
int lines;
char c;
lines=0;
while(c!=EOF)
{
c=getc(fp);
if(c=='\n')
lines++;
}
return lines;
}
int main(int argc, char *argv[])
{
FILE* fp;
int lines,i;
float* x;
float* fx;
lines=3;
fp=fopen("a.dat","r");
if(fp==NULL)
{
printf("Error opening file\n");
getchar();
return 0;
}
lines=countlines(fp); ////HERE IS THE DEMON if i don't call this
//the program gives expected output
///otherwise junk e.g all 0 or really big
//numbers
fx =(float*)malloc(lines*sizeof(float));
x=(float*)malloc(lines*sizeof(float));
if( fx==NULL)
{
printf("Error allocating memory\n");
getchar();
return 0;
}
if( x==NULL)
{
printf("Error allocating memory\n");
getchar();
return 0;
}
for(i=0; i<lines; i++)
fscanf(fp,"%f %f",&x[i],&fx[i]);
for(i=0; i<lines; i++)
printf("%f %f\n",x[i],fx[i]);
free(x);
free(fx);
fclose(fp);
getchar();
return 0;
}
I would really appreciate someone telling what i am doing wrong
thanks very much
oh and i'm compiling under dev c++ configured as C only