473,321 Members | 1,667 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,321 software developers and data experts.

A question about fscanf and feof !

I use the following program to read some strings from an inupt file,
and print them on the standard output.
But the last string in the input file always printed twice, what is
the reason and how can I make the last string be printed only once?
Anyone give me some suggestions?

input.txt:

abc def ghi
jk lm
sea

/* the string "sea" will be printed twice by the following program */
#include <stdio.h>

int main()
{
FILE *fp;
char str[256];
fp = fopen("input.txt", "r");
if (fp == NULL)
{
perror("Read file error!\n");
exit(1);
}

while (!feof(fp))
{
fscanf(fp, "%s", str);
printf("%s ", str);
}
fclose(fp);
return 0;
}

Oct 15 '06 #1
7 3952

ehui928 wrote:
I use the following program to read some strings from an inupt file,
and print them on the standard output.
But the last string in the input file always printed twice, what is
the reason and how can I make the last string be printed only once?
Anyone give me some suggestions?

input.txt:

abc def ghi
jk lm
sea

/* the string "sea" will be printed twice by the following program */
#include <stdio.h>

int main()
{
FILE *fp;
char str[256];
fp = fopen("input.txt", "r");
if (fp == NULL)
{
perror("Read file error!\n");
exit(1);
}

while (!feof(fp))
{
fscanf(fp, "%s", str);
printf("%s ", str);
}
fclose(fp);
return 0;
}
See Question 12.2 at http://c-faq.com.

Oct 15 '06 #2
Thank you !
Now it works fine!

Registered User 写道:
ehui928 wrote:
I use the following program to read some strings from an inupt file,
and print them on the standard output.
But the last string in the input file always printed twice, what is
the reason and how can I make the last string be printed only once?
Anyone give me some suggestions?

input.txt:

abc def ghi
jk lm
sea

/* the string "sea" will be printed twice by the following program */
#include <stdio.h>

int main()
{
FILE *fp;
char str[256];
fp = fopen("input.txt", "r");
if (fp == NULL)
{
perror("Read file error!\n");
exit(1);
}

while (!feof(fp))
{
fscanf(fp, "%s", str);
printf("%s ", str);
}
fclose(fp);
return 0;
}
See Question 12.2 at http://c-faq.com.
Oct 15 '06 #3
ehui928 wrote:
I use the following program to read some strings from an inupt file,
and print them on the standard output.
But the last string in the input file always printed twice, what is
the reason and how can I make the last string be printed only once?
Anyone give me some suggestions?

input.txt:

abc def ghi
jk lm
sea

/* the string "sea" will be printed twice by the following program */
#include <stdio.h>

int main()
{
FILE *fp;
char str[256];
fp = fopen("input.txt", "r");
if (fp == NULL)
{
perror("Read file error!\n");
exit(1);
}

while (!feof(fp))
{
fscanf(fp, "%s", str);
printf("%s ", str);
}
fclose(fp);
return 0;
}
First, the 'while (!feof(fp)) {}' is wrong. It would be fscanf which
errors but you printf anyway. Then catch the error and quit.

That is clearly wrong. Let me suggest something like..

while (fscanf(fp, "%s", str))
printf("%s ", str);

At end-of-file, fscanf will return 0 and no printf takes place.

P.S. I'd like to know where the 'while (!feof(fp)) {}' came from
originally and why it keeps popping up.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Oct 15 '06 #4
On Sun, 15 Oct 2006 10:47:13 -0400, Joe Wright
<jo********@comcast.netwrote:
<snip>
P.S. I'd like to know where the 'while (!feof(fp)) {}' came from
originally and why it keeps popping up.
Originally, as the FAQ semi-sarcastically indicates, Pascal. And
perhaps to an extent Ada, which provides BOTH the magic lookahead of
Pascal and the error/signal behavior of PL/I and FORTRAN by default
(and sort of by C, if you're careful about errorchecking).

Why it continues, two decades after Pascal has practically vanished
off the face of the earth*, is a harder question. Maybe Schildt? <G>

(* Yes, I know there are still some users and (even) implementors. But
you really have to look for them.)

- David.Thompson1 at worldnet.att.net
Nov 6 '06 #5
in 704529 20061106 083824 Dave Thompson <da*************@worldnet.att.netwrote:
>
Why it continues, two decades after Pascal has practically vanished
off the face of the earth*, is a harder question. Maybe Schildt? <G>

(* Yes, I know there are still some users and (even) implementors. But
you really have to look for them.)
Really? Ever heard of Delphi?
Nov 6 '06 #6
Joe Wright wrote:
while (fscanf(fp, "%s", str))
printf("%s ", str);

At end-of-file, fscanf will return 0 and no printf takes place.
fscanf returns EOF if input fails before any conversion takes
place, so this loop could run forever (and print the last string
many times).

Nov 6 '06 #7
Old Wolf wrote:
Joe Wright wrote:
> while (fscanf(fp, "%s", str))
printf("%s ", str);

At end-of-file, fscanf will return 0 and no printf takes place.

fscanf returns EOF if input fails before any conversion takes
place, so this loop could run forever (and print the last string
many times).
Thanks. Life is hopefully a learning experience. I have never used
fscanf() in my whole long life. That I would write something that
suggests my advice on how one might use it is clearly a brain fart. I
sincerely apologize to all who have had to read this.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 7 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: cylin | last post by:
Dear all, I can use c language function fscanf() to get a char. string. Ex: FILE *file=fopen("test.txt","r"); char data; while (!feof(file)) { fscanf(file,"%s",data); ... }
2
by: yezi | last post by:
Hi, ALl: The following code is to canculate 2 vector distance. Suppose the vectore is stored in some txt file like -1 0.34 0 0.045 1 0.98 1 0.01
7
by: bhanuprakash | last post by:
I am trying to use fscanf to read my test file. In my test file i sometimes have blank lines. When I try to read using the following format. fscanf(fp,"%\n",temp_str); If there is any blank...
2
by: naija | last post by:
When i am writing a simple c program-write to a file and read from it,fscanf not working. #include<stdio.h> int main() { FILE *ptr,*ptr1; int s,r; clrscr(); ptr=fopen("myfile.txt","w");...
10
by: Roman Zeilinger | last post by:
Hi I have a beginner question concerning fscanf. First I had a text file which just contained some hex numbers: 0C100012 0C100012 ....
11
by: mohdalibaig | last post by:
the program woks fine for a single record but for multiple records it isn't reading the entries properly... #include<stdio.h> #include<conio.h> #include<stdlib.h> #include<graphics.h> void...
3
by: Ranioo | last post by:
Hello everybody: i'm a new member in this site and i realy have a problem with c++. ok my problem is : i want to read text from a file and the text contains characters and decimal and...
42
by: Bill Cunningham | last post by:
I'm doing something wrong and all I know to do is turn to clc. I have a text file containing 2 doubles separated by a tab. ..26 0 Is the text. I want to read the two double and printf them...
3
by: godblessingme | last post by:
Hi, I'm getting some problems when using fscanf to read a file. This is a piece of the program code: #include <stdlib.h> #include <stdio.h> int main() {
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shllpp 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.