Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: while loop vs do while loop reading from the file issue Date: Wed, 07 Dec 2016 11:50:48 -0800 Organization: None to speak of Lines: 28 Message-ID: References: <52f1c174-6af1-4fda-9ff8-a5e2cf507b5f@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="f53e7a1e34684316d0e01429e9e9bbea"; logging-data="862"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX199CO/WGIdB6HIDWZHXghn0" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:1P2dqtmM5muzhnsZzGgiESoLMl4= sha1:FvITrcER1rjMYq+JXB8U6HoIFg0= Xref: csiph.com comp.lang.c:98287 Barry Schwarz writes: [...] > Example 1: Place the call to fscanf inside an if statement: > if (fscanf( cfPtr, "%d%29s%lf", &account, name, &balance ) > 0) > Now the following call to printf will not execute if fscanf fails. I'd write "== 3" rather than "> 0". fscanf() could return 1 or 2 if it's able to read only 1 or 2 items rather than the requested 3. You might want to treat reading 1 or 2 items differently from other kinds of failure, but for a small demo program like this it's probably best to treat anything other than 3 as an error. >> fscanf( cfPtr, "%d%29s%lf", &account, name, &balance ); > > Example 2: Insert an feof test just prior to the call to printf: > if (!feof( cfPtr )) > Same effect as above. Not quite. feof() will return false (0) if no more input is available due to an I/O error; in that case ferror() will return true. [...] -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"