The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > UNIX for Dummies Questions & Answers
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #2 (permalink)  
Old 03-11-2009
Corona688 Corona688 is offline
Registered User
  
 

Join Date: Aug 2005
Location: Saskatchewan
Posts: 1,972
Code tags for code please, they make the unreadable readable. [ code ] stuff [ /code ] without the extra spaces.

You get 'floating point error' when you divide by zero, check to see if things are getting parsed the way you expect.

You do not need to use fgetc to read in text data! Try scanf. Or better yet, sscanf. Read in data one line at a time then feed it through scanf to get what you want in one go.


Code:
char buf[512], garbage[512];
if(fgets(buf, 512, fp)==NULL0
{
  fprintf(stderr, "Can't read first line\n");
  return(1);
}

if(sscanf(buf, "%d", &load) != 1)
{
  fprintf(stderr, "Can't get load value\n");
  return(1);
}

while(fgets(buf, 512, fp)!=NULL)
{
  if(sscanf(buf, "%s %d %d", garbage, &weight, &value) != 3)
  {
    fprintf(stderr, "Couldn't parse line '%s'\n", buf);
    continue;
  }

  do_stuff();
}

You'll get purists complaining about scanf and its dangers but its far preferable to building your own integer-parsing routines. Used in this fashion it is fairly safe, with no risk of buffer overflows and none of the strange half-a-line-eaten problems plain scanf is infamous for.

Last edited by Corona688; 03-11-2009 at 11:25 PM.. Reason: adding more code