473,386 Members | 1,766 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,386 software developers and data experts.

question about gets() and feof().

hello everyone,
my code is like this:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
FILE *fp;
char str[128];

if((fp=fopen(argv[1], "r"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
while(!feof(fp)) {
if(fgets(str, 126, fp))
printf("%s", str);
else
printf("error.\n");
}
fclose(fp);
return 0;
}
////////////////////////////////////////////
if the input file is like this:
abc //first line
ddd //second line. and there is no "enter" in the end.
our code will run correctly.
if the input file is like this:
abc //first line
ddd //second line. in the end, press "enter"
//last line, this line is press "enter" in the second line.
//and there is none other key in the last line.
in this case, my code will output "error".

what's wrong?

sincerely

guo

Nov 15 '05 #1
3 1476
su*********@gmail.com wrote:
#include <stdio.h>
#include <stdlib.h> int main(int argc, char *argv[])
{
FILE *fp;
char str[128]; if((fp=fopen(argv[1], "r"))==NULL) {
What if argc is 1?
printf("Cannot open file.\n");
exit(1);
exit( EXIT_FAILURE );
}
while(!feof(fp)) {
if(fgets(str, 126, fp))
if( fgets(str,sizeof str,fp) )
printf("%s", str);
else
printf("error.\n");
}
fclose(fp);
return 0;
} what's wrong?


You have asked a FAQ:

http://www.eskimo.com/~scs/C-faq/q12.2.html

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 15 '05 #2
su*********@gmail.com wrote:
[...]
while(!feof(fp)) {
if(fgets(str, 126, fp))
printf("%s", str);
else
printf("error.\n");
} [...] if the input file is like this:
abc //first line
ddd //second line. in the end, press "enter"
//last line, this line is press "enter" in the second line.
//and there is none other key in the last line.
in this case, my code will output "error".

what's wrong?


A NULL return from fgets does not necessarily mean "error".

fgets() returns NULL if EOF is hit before reading anything. Since there
is nothing between the newline after "ddd" on the second line and EOF,
there are no more characters left to read. Hence NULL is returned even
though no error has occurred.

See also <http://www.eskimo.com/~scs/C-faq/q12.2.html> for further info
on another problem which you haven't hit yet.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>
Nov 15 '05 #3
su*********@gmail.com wrote:
hello everyone,
my code is like this:
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
FILE *fp;
char str[128];

if((fp=fopen(argv[1], "r"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
while(!feof(fp)) {
if(fgets(str, 126, fp))
printf("%s", str);
else
printf("error.\n");
}
The logic of this while loop is wrong. Replace it by:

while(fgets(str, sizeof str, fp))
{
printf("%s", str);
}
if(ferror(fp))
{
printf("error.\n");
}

fgets will also return NULL if end-of-file occurs before reading any
data in. This is not an error condition. You can tell if an error
occurred by calling ferror.
fclose(fp);
return 0;
}


--
Simon.
Nov 15 '05 #4

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

Similar topics

39
by: Teh Charleh | last post by:
OK I have 2 similar programmes, why does the first one work and the second does not? Basically the problem is that the program seems to ignore the gets call if it comes after a scanf call. Please...
10
by: Kieran Simkin | last post by:
Hi, I wonder if anyone can help me, I've been headscratching for a few hours over this. Basically, I've defined a struct called cache_object: struct cache_object { char hostname; char ipaddr;...
1
by: john | last post by:
Relatively new to C coding, so any help would greatly be appreciated. I'm having problems try to return my string array from my parsing function. When I do a printf I am getting the correct value...
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: ehui928 | last post by:
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...
42
by: mellyshum123 | last post by:
I need to read in a comma separated file, and for this I was going to use fgets. I was reading about it at http://www.cplusplus.com/ref/ and I noticed that the document said: "Reads characters...
20
by: Xavoux | last post by:
Hello all... I can't remind which function to use for safe inputs... gets, fgets, scanf leads to buffer overflow... i compiled that code with gcc version 2.95.2, on windows 2000 char tmp0 =...
20
by: ericunfuk | last post by:
If fseek() always clears EOF, is there a way for me to fread() from an offset of a file and still be able to detect EOF?i.e. withouting using fseek(). I also need to seek to an offset in the file...
16
by: pereges | last post by:
I'm getting a warning on my linux gcc compiler: /tmp/ccXgHa9s.o(.text+0x48): In function `main': : warning: the `gets' function is dangerous and should not be used. And here's where I used...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.