home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- 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
- From: ktf@bc3.GUN.de (Klaus ter Fehn)
- Subject: Re: fgets() sscanf() EOF confusion
- Organization: private
- Date: Wed, 30 Dec 1992 20:43:58 GMT
- Message-ID: <C03AxC.F8@bc3.GUN.de>
- References: <1992Dec30.160832.3769@coe.montana.edu>
- Lines: 61
-
- In article <1992Dec30.160832.3769@coe.montana.edu> sandy@cs.montana.edu (Sandy Pittendrigh) writes:
-
- >I know how to read a text file one character at a time,
- >and how to jump out of a loop when EOF is encountered,
-
- >but I'd like to do something like the following, and don't
- >know how to detect EOF when using fgets and sscanf.
-
-
- 1 >while(!feof(inFile))
- 2 > {
- 3 > fgets(line,80,inFile);
- 4 > sscanf(line,"%d %d %d %d", &x, &y, &z);
- 5 > if(eof(inFile) /* But this doesn't work */
- 6 > {
- 7 > doSomething(x,y,z);
- 8 > break;
- 9 > }
- 10 > else doSomething(x,y,z);
- 11 > }
-
- >Is this a resonable concept?
-
- delete line 7
- change line 5 to 'if (feof(inFile))'
- drop one '%d' in line 4
- move line 4 behind line 9
- drop the 'else' on line 10:
-
- 1 while(!feof(inFile))
- 2 {
- 3 fgets(line,80,inFile);
- 4 if(feof(inFile))
- 5 {
- 6 break;
- 7 }
- 8 sscanf(line,"%d %d %d", &x, &y, &z);
- 9 doSomething(x,y,z);
- 10 }
-
- This for your program-code - but you're reading 3 Integers at a time.
- Above you mentioned, that you're trying to read one character at a time
- out of an ascii-file. For that the following code will do so:
-
- 1 int character;
- 2 /* ... */
- 3 while ((character = fgetc(inFile)) != EOF)
- 4 {
- 5 doSomethingWithChar(character);
- 6 }
-
- Note, that you should use an int-var for reading with fgetc, because it
- return 0..255, if ASCII-Values are read and EOF (often -1) if end of
- file was encountered.
-
- Greetings...
- --
- Klaus ter Fehn <ktf@bc3.GUN.de>
- Neanderstr. 4 {mcshh,smurf,unido}!easix!bc3!ktf
- 4000 Duesseldorf 1
- FRG / Germany Tel.: +49-211-676331
-