473,725 Members | 2,295 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Determining EOF using fseek()?

Hey,

I was wondering if it was possible to determine if you hit 'EOF' using
fseek? I'm using fseek to traverse through the file from start to end
and capturing the data into a linked list structure. However, my loop
doesn't seem to work well - it totally fumbles out actually:

while ((a = fseek(fp,0,SEEK _CUR)) == 0){
// code here
}

Its quite important for me not to disrupt the current position of the
cursor since I rely on that to fetch the data from the text file. I
thought that the loop would work fine since fseek only returns a
non-zero integer on an error but unfortunately this is not the case.
Anyone with suggestions with using fseek() or some other function?

Any help would be greatly appreciated! Thanks.
Nov 14 '05 #1
10 12922
On Fri, 27 Aug 2004 14:08:23 GMT,
Orion <wo****@bigpond .net.au> wrote:

Hey,

I was wondering if it was possible to determine if you hit 'EOF' using
fseek? I'm using fseek to traverse through the file from start to end
and capturing the data into a linked list structure. However, my loop
doesn't seem to work well - it totally fumbles out actually:

while ((a = fseek(fp,0,SEEK _CUR)) == 0){
// code here
}


I wouldn't expect this would ever return an error as long as fp is a valid
FILE pointer representing a seekable file. The normal way to determine
eof is to read from the file and see if it returns an eof indication.

Villy
Nov 14 '05 #2
Orion wrote:
Hey,

I was wondering if it was possible to determine if you hit 'EOF' using
fseek? I'm using fseek to traverse through the file from start to end
and capturing the data into a linked list structure. [...]


If you're reading the whole file "from start to end," why
are you using fseek() at all? Just keep calling fgets() or
fread() or whatever you're using to soak up the data, and when
you get to end-of-file the function will tell you so[*] by
returning the value EOF.
[*] The EOF return value can also indicate an actual I/O
error rather than end-of-file. For belt-and-suspenders
certainty, you can use feof() or ferror() to figure out
what the EOF value actually meant.

--
Er*********@sun .com

Nov 14 '05 #3
Orion wrote:
Hey,

I was wondering if it was possible to determine if you hit 'EOF' using
fseek? I'm using fseek to traverse through the file from start to end
and capturing the data into a linked list structure. However, my loop
doesn't seem to work well - it totally fumbles out actually:

while ((a = fseek(fp,0,SEEK _CUR)) == 0){
// code here
}

Its quite important for me not to disrupt the current position of the
cursor since I rely on that to fetch the data from the text file. I
thought that the loop would work fine since fseek only returns a
non-zero integer on an error but unfortunately this is not the case.
Anyone with suggestions with using fseek() or some other function?

Any help would be greatly appreciated! Thanks.


Of course, there is feof(fp) for these purposes.

--
Karthik.
Nov 14 '05 #4
>Orion wrote:
I was wondering if it was possible to determine if you hit 'EOF' using
fseek?

(The correct answer is "no", as I believe others have already
posted. Unix-like systems allow a quite simple demonstration: open
a file for both reading and writing, seek to a position many
gigabytes past the existing EOF, and write one byte. The file is
suddenly that much longer. [Note that modern Unix-like systems
support multi-terabyte files. Of course, you cannot use fseek()
to do this unless LONG_MAX is more than 2147483647, e.g., on Itanium
or Alpha.] Since you can seek to any location, including nonexistent
beyond-current-EOF locations, in order to extend a file, it
necessarily follows that seeks past the existing EOF do not fail
-- at least if the file is open for writing. As it happens, this
holds for read-only files as well.)

In article <news:41300fa4$ 1@darkstar>
Karthiik Kumar <ka************ *****@yahoo.com > wrote: Of course, there is feof(fp) for these purposes.


feof(fp) is not "for those purposes". The feof() function has only
one purpose: after an attempt to read fails, feof() and ferror()
distinguish between the two possible reasons for such a failure: EOF,
or error.

The read failure *must* occur first, though.
--
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
Karthiik Kumar <ka************ *****@yahoo.com > wrote:

Of course, there is feof(fp) for these purposes.


No, there isn't. feof() doesn't tell you if trying to read *will*
return EOF, it only tells you if a previous read *already returned* EOF.

-Larry Jones

I've never seen a sled catch fire before. -- Hobbes
Nov 14 '05 #6
Orion <wo****@bigpond .net.au> wrote in message news:<rf******* **********@news-server.bigpond. net.au>...
Hey,

I was wondering if it was possible to determine if you hit 'EOF' using
fseek? I'm using fseek to traverse through the file from start to end
and capturing the data into a linked list structure. However, my loop
doesn't seem to work well - it totally fumbles out actually:

while ((a = fseek(fp,0,SEEK _CUR)) == 0){
// code here
}

Its quite important for me not to disrupt the current position of the
cursor since I rely on that to fetch the data from the text file. I
thought that the loop would work fine since fseek only returns a
non-zero integer on an error but unfortunately this is not the case.
Anyone with suggestions with using fseek() or some other function?

Any help would be greatly appreciated! Thanks.


Hi

To read all characters from a text file upto EOF better u can go
for feof
function. Iam giving an example so that u can understand

Method1:

FILE *Fp;
int ch;

Fp=fopen("c:\\t est.txt","rb");

while((ch=fgetc (Fp))!=EOF)
printf("%c",ch) ;

fclose(Fp);

Method2:

File *Fp;
char ch;

Fp=fopen("c:\\t est.txt","rb");

ch=fgetc(Fp);

while(!feof(Fp) )
{

printf("%c",ch) ;
ch=fgetc(Fp);
}

fclose(Fp);

The above two methods will work correctly. The reason EOF value is
FFFF.
It will go beyond the range. so normally an unsigned char cannot able
to hold the value of EOF. So u can get an logical error while reading
entire file becus
fgetc will treat EOF as character. Hope these ideas will make u
clear.

regards,

Anand.
Nov 14 '05 #7
In article <news:cd******* *************** **@posting.goog le.com>
Anand <an********@yah oo.co.in> wrote:
To read all characters from a text file upto EOF better u can go
for feof function.
This is not a good idea.
Method1: [snipped -- it should work, although it seems peculiar to fopen()
a file named "test.txt" with "rb" -- binary -- mode.]
Method2:

File *Fp;
char ch;

Fp=fopen("c:\\t est.txt","rb");

ch=fgetc(Fp);

while(!feof(Fp) )
{

printf("%c",ch) ;
ch=fgetc(Fp);
}

fclose(Fp);

The above two methods will work correctly.
The second method could loop forever if run on an input file that
is (e.g.) on a bad floppy disk. (Remember floppies? :-) ) Suppose
fgetc() attempts to read a sector off the floppy, but the sector
is bad. The read will fail, but *not* because of end-of-file.
The C standard then suggests that feof(Fp) should return 0, and
ferror(Fp) should return some nonzero value. This is indeed what
happens on some real systems.
The reason EOF value is FFFF.
Actually, EOF is a macro "#define"d in <stdio.h> to some negative
integral value (often just -1, but any negative integral value is
allowed).
It will go beyond the range. so normally an unsigned char cannot able
to hold the value of EOF.


The value EOF expands to may or may not be outside the range of a
plain (and thus possibly signed) "char". It is indeed outside the
range of an unsigned char, and if EOF is #defined to -1, the result
of:

unsigned char uc = EOF;

is to set uc to UCHAR_MAX, by definition. But this is rarely 0xffff;
more commonly, this is 0xff.

As a rule, if you ever see a "while (!feof(...))" loop in C, the
code is going to be wrong. The only place you should normally see
feof() or ferror() calls is inside an "if (...)". One can construct
exceptions to this rule, but in real code, it works pretty well:
be very suspicious of any loop controlled by an feof() call.
--
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 #8


Chris Torek wrote:
In article <news:cd******* *************** **@posting.goog le.com>
Anand <an********@yah oo.co.in> wrote:
To read all characters from a text file upto EOF better u can go
for feof function.

This is not a good idea.

Method1:


[snipped -- it should work, although it seems peculiar to fopen()
a file named "test.txt" with "rb" -- binary -- mode.]

Method2:

File *Fp;
char ch;

Fp=fopen("c:\\t est.txt","rb");

ch=fgetc(Fp);

while(!feof(Fp) )
{

printf("%c",ch) ;
ch=fgetc(Fp);
}

fclose(Fp);

The above two methods will work correctly.

The second method could loop forever if run on an input file that
is (e.g.) on a bad floppy disk. (Remember floppies? :-) ) Suppose
fgetc() attempts to read a sector off the floppy, but the sector
is bad. The read will fail, but *not* because of end-of-file.
The C standard then suggests that feof(Fp) should return 0, and
ferror(Fp) should return some nonzero value. This is indeed what
happens on some real systems.


OK, you lost me here. I would think that if the source file or media
is corrupt, that *nothing* in C would be guaranteed to work correctly.
Why would one method (at the C level) work better than another?

The reason EOF value is FFFF.

Actually, EOF is a macro "#define"d in <stdio.h> to some negative
integral value (often just -1, but any negative integral value is
allowed).

It will go beyond the range. so normally an unsigned char cannot able
to hold the value of EOF.

The value EOF expands to may or may not be outside the range of a
plain (and thus possibly signed) "char". It is indeed outside the
range of an unsigned char, and if EOF is #defined to -1, the result
of:

unsigned char uc = EOF;

is to set uc to UCHAR_MAX, by definition. But this is rarely 0xffff;
more commonly, this is 0xff.

As a rule, if you ever see a "while (!feof(...))" loop in C, the
code is going to be wrong. The only place you should normally see
feof() or ferror() calls is inside an "if (...)". One can construct
exceptions to this rule, but in real code, it works pretty well:
be very suspicious of any loop controlled by an feof() call.


Again, I don't follow your reasoning. The "if (something)" and
"while (something)" constructs both expect "something" to be a logical
expression (evaluates either to 0 or non-0). Why is "if (feof(...))"
better than "while (feof(...))" ?

--
Ron Collins
Raytheon Air Defense/RTSC/BCS

Nov 14 '05 #9
RCollins wrote:


Chris Torek wrote:
In article <news:cd******* *************** **@posting.goog le.com>
Anand <an********@yah oo.co.in> wrote:
To read all characters from a text file upto EOF better u can go
for feof function.


This is not a good idea.

Method1:

[snipped -- it should work, although it seems peculiar to fopen()
a file named "test.txt" with "rb" -- binary -- mode.]

Method2:

File *Fp;
char ch;

Fp=fopen("c:\\t est.txt","rb");

ch=fgetc(Fp);

while(!feof(Fp) )
{

printf("%c",ch) ;
ch=fgetc(Fp); }

fclose(Fp);

The above two methods will work correctly.


The second method could loop forever if run on an input file that
is (e.g.) on a bad floppy disk. (Remember floppies? :-) ) Suppose
fgetc() attempts to read a sector off the floppy, but the sector
is bad. The read will fail, but *not* because of end-of-file.
The C standard then suggests that feof(Fp) should return 0, and
ferror(Fp) should return some nonzero value. This is indeed what
happens on some real systems.

OK, you lost me here. I would think that if the source file or media
is corrupt, that *nothing* in C would be guaranteed to work correctly.
Why would one method (at the C level) work better than another?

The reason EOF value is FFFF.


Actually, EOF is a macro "#define"d in <stdio.h> to some negative
integral value (often just -1, but any negative integral value is
allowed).

It will go beyond the range. so normally an unsigned char cannot able
to hold the value of EOF.


The value EOF expands to may or may not be outside the range of a
plain (and thus possibly signed) "char". It is indeed outside the
range of an unsigned char, and if EOF is #defined to -1, the result
of:

unsigned char uc = EOF;

is to set uc to UCHAR_MAX, by definition. But this is rarely 0xffff;
more commonly, this is 0xff.

As a rule, if you ever see a "while (!feof(...))" loop in C, the
code is going to be wrong. The only place you should normally see
feof() or ferror() calls is inside an "if (...)". One can construct
exceptions to this rule, but in real code, it works pretty well:
be very suspicious of any loop controlled by an feof() call.

Again, I don't follow your reasoning. The "if (something)" and
"while (something)" constructs both expect "something" to be a logical
expression (evaluates either to 0 or non-0). Why is "if (feof(...))"
better than "while (feof(...))" ?


The canonical method for reading a file to the end is..
int c;
FILE *in;
....
while ((c = fgetc(in)) != EOF) {

}
Now when fgetc() detects EOF it is before the loop executes for that
character. After the loop test "if (!feof(in)) {}" to know whether
EOF meant end-of-file or was an error.

If the control was "while (!feof(...))" with "c = fgetc(in)" inside
the loop, the loop is executed with c == EOF which is probably not
what you want.

--
Joe Wright mailto:jo****** **@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #10

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

Similar topics

62
6233
by: Christopher Benson-Manica | last post by:
On thinking about the "replace a word in a file" thread, I wondered how easy it would be to accomplish the same thing with only one file pointer. This led me to some questions... "For a text stream, offset must be zero, or a value returned by ftell (in which case origin must be SEEK_SET)." If offset is a value returned by ftell (which returns the current file position), and origin is SEEK_SET, then fseek() sets the position to the...
15
16110
by: TJ Walls | last post by:
Hello All, I am baffled ... I am trying to improve the speed of a program that I have written that performs random access within a file. It relies heavily on fseek and is very slow. To test, I wrote the following test program which just writes the numbers 1-167721 sequentially to a binary file: #include <stdio.h> #include <stdlib.h>
14
2757
by: googler | last post by:
Is there any C library function that returns the size of a given file? Otherwise, is there a way in which file size can be determined in a C program? I need to get this for both Linux and Windows platforms, so a generic solution is what I am looking for. Thanks for your help.
2
3551
by: cedarson | last post by:
I am writing a program and have been instructeed to use the 'fseek', 'ftell', and 'stat' functions, however, after looking in the online manual for each of these, I am still unsure on how to use them. In my program, I am to write a code that opens a file, uses 'stat' to determine the file size, use 'fseek' to move the offset of the pointer, and finally use 'ftell' to obtain the file pointer index. Will someone please help? Again, thanks...
10
5977
by: Kenneth Brody | last post by:
I recently ran into an "issue" related to text files and ftell/fseek, and I'd like to know if it's a bug, or simply an annoying, but still conforming, implementation. The platform is Windows, where text files use CF+LF (0x0d, 0x0a) to mark end-of-line. The file in question, however, was in Unix format, with only LF (0x0a) at the end of each line. First, does the above situation already invoke "implementation defined" or "undefined"...
3
2949
by: Chen ShuSheng | last post by:
HI, I am now study a segment of codes: ------------------------ printf("%p\t",fp); /*add by me*/ fseek(fp, 0L, SEEK_END); /* go to end of file */ printf("%p\t",fp); /*add by me*/ last = ftell(fp); cout<<"last="<<last<<"\t"; /*add by me*/ -------------------------
14
3704
by: Maria Mela | last post by:
Hello everyone... I´ve a problem with my code, when i put this lines: recsize = sizeof(p1); fseek(fp,-recsize,SEEK_CUR); fwrite(&p1,sizeof(p1),1,fp); getch(); The file was saved with correct values and with some windows informations too!?
6
6154
by: ericunfuk | last post by:
A basic question: When the documentation says "fseek() clears EOF indecator, does it mean when you seek over EOF, EOF is no longer at the original position and hence removed?Say, after I seek over the original EOF, when I fread() from a previous position that I know is before the EOF then fread will not be able to tell if it has encountered the original EOF? Thank YOU!
20
7541
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 frequently(forwards and backwards) and do fread() from that offset. Or better still, could anyone let me know some good ways to achieve what I need to do as above?Can I get hold of the file and being able to read in without using fread()? Using...
0
8889
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9179
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9116
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8099
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.