[A89] reading from text variables in C


[Prev][Next][Index][Thread]

[A89] reading from text variables in C




OK, I'm writing a program to learn some C.  I have a text file on the
calculator that looks like this:

;words
#
;words
#
...

words = arbitrary text
# = a float or an int
... = et cetera

It's basically either lines beginning with semicolons (think of them as
comments) or numbers.  Now, I know gets() should work fine for this but
it doesn't.  First off, I think it's broken because it keeps reading
after '\r' characters.  Also, it keeps '\r' characters in the output
string, and I think that screws up atof().  So I wrote this to get around
it:

//meant to replace gets()
char *read_string(char *buffer, int length, FILE *file_ptr)
{
char c;
int index = 0;

//initialize c and clear the buffer
c = (char)getc(file_ptr);
memset(buffer, ' ', length - 1);

while((c != '\r')&&(c != EOF)&&(length > index))
{
buffer[index] = c;
c = (char)getc(file_ptr);
index++;
}

if(c == EOF)
{
return NULL;
}
else
{
return buffer;
}
} //end function


I used the following code to read the file:

while((read_string(buffer, 30, file_ptr) != NULL)&&(index < TEMP_SIZE))
{
 c = strchr(buffer, ';');
 //c = NULL iff there are no semicolons in buffer
 //strlen = 0 iff the length of buffer is zero (not including '\0')
 //in other words, ignore buffer if it has a semicolon or is empty
 if((c == NULL)&&strlen(buffer))
 {
  temp[index] = atof(buffer);
  //is_nan() returns true iff its argument is NAN (Not_a_Number)
  //if(is_nan(temp[index]))
  //{
   //puts("error reading number\n");
   printf("%s  %f\n", buffer, temp[index]);
  //}
  index++;
 }
} //end while


Now to my questions:

When I run the program, it spits out two columns of data, one from the
string buffer, one from the float temp (see the printf() above).  The
string column looks fine but the float column is some garbage and
1*undef.  What is going wrong?  Note that though the numbers are
different (0, -.27, 218, etc.) the float column looks the same for each.

I have 6 numbers that I want to read, but my program only reads 5. 
TEMP_SIZE is sufficiently large.  What is going wrong?


jon "1*undef" k.
________________________________________________________________
GET INTERNET ACCESS FROM JUNO!
Juno offers FREE or PREMIUM Internet access for less!
Join Juno today!  For your FREE software, visit:
http://dl.www.juno.com/get/web/.