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

fgets on an empty file

Hi,

fgets returns NULL on error and the first argument on success. I
want to open a file and read it using fgets. This is returning NULL,
when the file is empty. Is there anyway to circumvent this problem
without changing the function call to fscanf or something else?
Thanks in advance.
Rgds,
Karthick S.
Nov 14 '05 #1
4 14036
Karthick S. <ka*******@spymac.com> wrote:
fgets returns NULL on error and the first argument on success. I
want to open a file and read it using fgets. This is returning NULL,
when the file is empty. Is there anyway to circumvent this problem
without changing the function call to fscanf or something else?


What's the problem? If the file is empty you hit EOF immediately
and fgets() returns NULL (not only on error). If there's something
in the file fgets() also will return NULL, but only later after you
have read everything from the file. So, you must always be prepared
to get NULL when you use fgets(), empty or non-empty file.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.toerring.de
Nov 14 '05 #2
On 16 Aug 2004 07:10:46 -0700, ka*******@spymac.com (Karthick S.)
wrote:
Hi,

fgets returns NULL on error and the first argument on success. I
want to open a file and read it using fgets. This is returning NULL,
when the file is empty. Is there anyway to circumvent this problem
without changing the function call to fscanf or something else?


Whenever fgets returns NULL, you should use feof() to determine if it
was an error or an end of data condition.
<<Remove the del for email>>
Nov 14 '05 #3
Je***********@physik.fu-berlin.de wrote in message news:<2o************@uni-berlin.de>...

What's the problem? If the file is empty you hit EOF immediately
and fgets() returns NULL (not only on error). If there's something
in the file fgets() also will return NULL, but only later after you
have read everything from the file. So, you must always be prepared
to get NULL when you use fgets(), empty or non-empty file.

Regards, Jens


Hi,

I am attaching a code snippet:

/*****************************Code Begins*********************/
int ReadFile(char **r_pstrState)
{
int iRetVal = SUCCESS;
FILE *fp = (FILE*) NULL;
char strErrMesg[1024];

fp = fopen(MYFILE, "r");
if(NULL == fp)
{
sprintf(strErrMesg, "Opening the file %s failed. Error: %s",
CURRSTATECONF, strerror(errno));
fputs(strErrMesg, stderr);
fputs("\n", stderr);
iRetVal = FAILURE;
return(iRetVal);
}
errno = 0;
if(fgets(*r_pstrState, 5, fp) == NULL)
{
sprintf(strErrMesg, "Reading from the file %s failed. Error: %s",
CURRSTATECONF, strerror(errno));
fputs(strErrMesg, stderr);
fputs("\n", stderr);
iRetVal = FAILURE;
return(iRetVal);
}
iRetVal = SUCCESS;
return(iRetVal);
}

int main(void)
{
char strArr[6];

return(ReadFile(&strArr));
}
/*****************************Code Ends***********************/

Now if the file that I had #defined as MYFILE is blank, then I get
the error message:

Reading from the file <path to file> failed. Error: Success.

I would like to know the reason for this.

Thank you.
Rgds,
Karthick S.
Nov 14 '05 #4
In article <news:ef**************************@posting.google. com>
Karthick S. <ka*******@spymac.com> wrote:
[snippage, and edited-for-space-reasons]
if(fgets(*r_pstrState, 5, fp) == NULL) {
sprintf(strErrMesg,
"Reading from the file %s failed. Error: %s",
CURRSTATECONF, strerror(errno));
This is not a good idea. The fgets() function is never guaranteed
to set errno to anything, even on error. In practice, on real
operating systems, reading from a file does tend to set errno on
error, but not on EOF.
[at EOF] I get the error message:
Reading from the file <path to file> failed. Error: Success.


This is quite unsurprising.

Do not inspect errno after fgets() fails. If you want to know
*why* fgets() has failed, use feof() and ferror() to distinguish
between "fgets() failed because of end-of-file" and "fgets() failed
because of error reading file".

Note that you should not use feof() *before* getting an input
failure of some sort, because feof() does not predict input failure
due to end of file, but rather "postdict" it: *after* failure, one
of feof() or ferror() should be true.

Note again that Standard C does not guarantee anything useful
in errno even in the ferror() case, so something like:

if (fgets(*r_pstrState, 5, fp) == NULL) {
if (feof(fp)) {
... normal end of file case ...
} else {
sprintf(strErrMesg,
"Reading from the file %s failed. The system "
"most recently reported \"%s\", which may or "
"may not have anything to do with the failure.",
CURRSTATECONF, strerror(errno));
...
}
}

will include the (potential) errno-based information along with a
caveat.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #5

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

Similar topics

6
by: Tanel | last post by:
Hello, I need to read a result of the first script (that takes some time to run) from the second script so that the first script doesn't block the second. Here is a short example. do_smth_else()...
5
by: Trying_Harder | last post by:
Generally we have function names briefly indicating their actions. In similar lines I expected `fopen' mean "File Open", fgets "File Get String" etc. I was told recently this wasn't the case...
8
by: Magix | last post by:
Hi, I'm not too sure on reading specify string with the first < > from file stream,and make the file pointer go to next line, with fgets. or any better idea. E.g let say text.txt has...
20
by: TTroy | last post by:
Hello, I have found some peculiar behaviour in the fgets runtime library function for my compiler/OS/platform (Dev C++/XP/P4) - making a C console program (which runs in a CMD.exe shell). The...
6
by: AMT2K5 | last post by:
Hello. I have a file (for a school assignment) with the following format and delimiter format. Each record in the file has the following format: 123423454567987,29873,James,Harry,St....
0
by: yawnmoth | last post by:
Say you open a socket connection with fsockopen. Normally, subsequent calls to fgets are going to block until input is ready. Unless, of course, socket_set_blocking is used to disable blocking...
32
by: FireHead | last post by:
Hello C World & Fanatics I am trying replace fgets and provide a equavivalant function of BufferedInputReader::readLine. I am calling this readLine function as get_Stream. In the line 4 where...
9
by: Justme | last post by:
Novice programmer needs help with using fgets to read and ignore the first two lines of a file. I've gone thru the previous posting regarding fgets, but none of them seems to help my situation. I...
12
by: Krumble Bunk | last post by:
Hi all, Having some trouble with a seemingly-simple task. Need to have a basic CLI functionality as per: prompt <- \n prompt <- \n promptquit <- should quit as per my snippet, but...
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: 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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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.