home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / lang / c / 19080 < prev    next >
Encoding:
Text File  |  1992-12-31  |  2.0 KB  |  72 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!zaphod.mps.ohio-state.edu!cs.utexas.edu!qt.cs.utexas.edu!yale.edu!ira.uka.de!smurf.sub.org!easix!bc3!ktf
  3. From: ktf@bc3.GUN.de (Klaus ter Fehn)
  4. Subject: Re: fgets() sscanf() EOF confusion
  5. Organization: private
  6. Date: Wed, 30 Dec 1992 20:43:58 GMT
  7. Message-ID: <C03AxC.F8@bc3.GUN.de>
  8. References: <1992Dec30.160832.3769@coe.montana.edu>
  9. Lines: 61
  10.  
  11. In article <1992Dec30.160832.3769@coe.montana.edu> sandy@cs.montana.edu (Sandy Pittendrigh) writes:
  12.  
  13. >I know how to read a text file one character at a time, 
  14. >and how to jump out of a loop when EOF is encountered,
  15.  
  16. >but I'd like to do something like the following, and don't 
  17. >know how to detect EOF when using fgets and sscanf.
  18.  
  19.  
  20.     1    >while(!feof(inFile))
  21.     2    >  {
  22.     3    >  fgets(line,80,inFile);
  23.     4    >  sscanf(line,"%d %d %d %d", &x, &y, &z);
  24.     5    >  if(eof(inFile) /* But this doesn't work */
  25.     6    >   {
  26.     7    >   doSomething(x,y,z);
  27.     8    >   break;
  28.     9    >   }
  29.    10    >  else doSomething(x,y,z);
  30.    11    >  }
  31.  
  32. >Is this a resonable concept? 
  33.  
  34. delete line 7
  35. change line 5 to 'if (feof(inFile))'
  36. drop one '%d' in line 4
  37. move line 4 behind line 9
  38. drop the 'else' on line 10:
  39.  
  40.     1    while(!feof(inFile))
  41.     2    {
  42.     3            fgets(line,80,inFile);
  43.     4            if(feof(inFile))
  44.     5            {
  45.     6                    break;
  46.     7            }
  47.     8            sscanf(line,"%d %d %d", &x, &y, &z);
  48.     9            doSomething(x,y,z);
  49.    10    }
  50.  
  51. This for your program-code - but you're reading 3 Integers at a time.
  52. Above you mentioned, that you're trying to read one character at a time
  53. out of an ascii-file. For that the following code will do so:
  54.  
  55.     1    int character;
  56.     2    /* ... */
  57.     3    while ((character = fgetc(inFile)) != EOF)
  58.     4    {
  59.     5        doSomethingWithChar(character);
  60.     6    }
  61.  
  62. Note, that you should use an int-var for reading with fgetc, because it
  63. return 0..255, if ASCII-Values are read and EOF (often -1) if end of 
  64. file was encountered.
  65.  
  66. Greetings...
  67. -- 
  68. Klaus ter Fehn        <ktf@bc3.GUN.de>
  69. Neanderstr. 4        {mcshh,smurf,unido}!easix!bc3!ktf
  70. 4000 Duesseldorf 1
  71. FRG / Germany        Tel.: +49-211-676331
  72.