E
Eric Sosman
Alan said:Hi all,
I've been trying to read a text file into an array without much
success. The following is part of "main" and all appears OK until the
statement while (fgets(str,20,fp) !=NULL)
Sometimes it works fine and the file xtl.dat (argv[1]) is read in
perfectly and the program performs as expected. But more often than not,
it appears to treat the first line of xtl.dat (which is "0.51400) as
NULL and skips the rest of the file.
Can anyone see what I've done wrong?
Thanks
Alan
#include "stdio.h"
#include <math.h>
#include <stdlib.h>
float f[140] ;
main(argc,argv)
int argc ;
char *argv[] ;
Not the source of your problem, but this is very old-
fashioned, almost two decades out of date. Replace all
three lines with
int main(int argc, char *argv[])
.... to use modern style (where "modern" means "more recent
than the Reagan administration").
{
FILE *fopen() , *fp ;
float freq=20.0,tol=0.0005 ;
float freqin(),tolin() ;
char *str,c ;
Here's the beginning of your problem, although the problem
doesn't occur quite yet. `str' is a variable that can point
to a char, and you plan to use it to point to the first of a
bunch of chars. But what does it point at NOW? You haven't
given it a value, so its value is indeterminate. Informally,
it "points to nowhere," which is a perfectly acceptable state
of affairs at the moment, but ...
int i=0,j,k,size=120 ;
if ((fp=fopen(argv[1],"r")) == NULL) {
printf("No crystal list file %s\n",argv[1]) ; exit(1) ;
}
while (fgets(str,20,fp) != NULL) {
.... but now fgets() will try to store as many as 20 characters
at and after the place `str' points to. Where does `str' point?
See above, and see Question 7.2 in the comp.lang.c Frequently
Asked Questions (FAQ) list at said:f=atof(str) ;
Also not the source of your problem, but strtod() is more
robust than atof(), because it lets you discover the error
when the input looks like "1.2.3" or "x44".
for (i=0;i<130;i++) {
fgets(str,20,fp) ;
Same problem as above: where does `str' point?
f = atof(str) ;
Note that the first time through the loop you will wipe
out the value that was previously stored in f[0]. Is that
what you meant to do? If so, why did you bother storing
the earlier f[0] value?
printf(" %10s %3.6f %d",str,f,i) ;
}
fclose(fp) ;