Re: Programming in standard c
- From: "Bart C" <bc@xxxxxxxxxx>
- Date: Thu, 27 Dec 2007 21:32:56 GMT
"Eric Sosman" <esosman@xxxxxxxxxxxxxxxxxxxx> wrote in message
news:4fSdnWveWJLpLu7anZ2dnUVZ_s-pnZ2d@xxxxxxxxxxxxxx
Bart C wrote:
unsigned int getfilesize(FILE* handle)
{
unsigned int p,size;
p=ftell(handle); /*p=current position*/
fseek(handle,0,2); /*get eof position*/
size=ftell(handle); /*size in bytes*/
fseek(handle,p,0); /*restore file position*/
return size;
}
What is wrong with this, is it non-standard? (Apart from the likely 4Gb
limit)
Several things are wrong with it, even apart from the
possible 64KB limit.
I'll let that go.
Zeroth, you should have #include'd <stdio.h>. I'll let
you get away with this one, though, on the grounds that since
This is a code fragment. Assume headers are included for all C library
calls.
First, there's no error checking. None, nada, zero, zip.
I wasn't aware there was much to go wrong. But I will have a look. At worst
it will return the wrong file size; I'll make it return all 0's or or 1's or
something.
Second, ftell() returns a long. When you store the long
I'll change the types to long too, since it can't go past 2GB-1 anyway.
Third, what are the magic numbers 2 and 0 that you use
as the third arguments in the fseek() calls? My guess is
that they are the expansions of the macros SEEK_END and
SEEK_CUR on some system you once used, and that you've
decided for some bizarre reason to avoid using the macros.
Close. The code existed in a non-C language, but using the C runtime,
without access to the headers and it was easiest to plug in these constants.
Converted to C (and tested) for the post.
Fourth, for a text stream the value returned by ftell() is
not necessarily a byte count; it is a value with an unspecified
encoding. Calling it a "file size" makes unwarranted assumptions.
My assumption is the file is in binary mode; and my wrapper of the fopen()
function ensures that.
Fifth, there's 7.19.9.2p3: "A binary stream need not...
Sixth, for a binary stream there may be an unspecified...
I don't get these. There are known issues when used with files currently
open for writing. And I know the host OS in *my* case. But yes, anyone
attempting to use this code on their OS should be aware of limitations.
But other than that, it looks pretty good.
Thanks (?)
Bart
.
- Follow-Ups:
- Re: Programming in standard c
- From: jameskuyper
- Re: Programming in standard c
- References:
- Programming in standard c
- From: jacob navia
- Re: Programming in standard c
- From: jameskuyper
- Re: Programming in standard c
- From: jacob navia
- Re: Programming in standard c
- From: user923005
- Re: Programming in standard c
- From: Bart C
- Re: Programming in standard c
- From: Eric Sosman
- Programming in standard c
- Prev by Date: Re: Happy christmas
- Next by Date: Re: Programming in standard c
- Previous by thread: Re: Programming in standard c
- Next by thread: Re: Programming in standard c
- Index(es):
Relevant Pages
|