473,698 Members | 2,631 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Size of a File

Hi,
I 'm new to C programming and 'm stuck somewhere.
I want to find the size of a file.
I couldn't find a proper way of doing it.
What I was planning to do is...
Open the requested file,
default position is 1st byte.
Now I use fseek() and move it till the send of the file.
Than I use ftell() to get the current position in the file.

this should return the num of bytes (length / size) of the file.

Is this a proper way to do?
Is there any efficient way to do so?

Thanks

Sep 7 '08 #1
20 2480
Ashit Vora wrote:
Hi,
I 'm new to C programming and 'm stuck somewhere.
I want to find the size of a file.
I couldn't find a proper way of doing it.
What I was planning to do is...
Open the requested file,
default position is 1st byte.
Now I use fseek() and move it till the send of the file.
Than I use ftell() to get the current position in the file.
That's what I would do, too (and what I was suggested to do when I had
the same problem some time ago).

I don't know of any other way (to do it portably). There may be
"better" tricks using platform specific APIs (like POSIX) though.

Daniel

--
Done: Arc-Bar-Cav-Sam-Val-Wiz, Dwa-Elf-Gno-Hum-Orc, Law-Neu-Cha, Fem-Mal
To go: Hea-Kni-Mon-Pri-Ran-Rog-Tou
Sep 7 '08 #2
>I 'm new to C programming and 'm stuck somewhere.
>I want to find the size of a file.
First of all, you need to define what *IS* the size of a file.
It's not a trivial question.

Is it the amount of space it takes on disk, including partially unused
blocks? Does that include the size of a directory slot? Inode?
Is it the number of bytes you can read from the file in binary mode?
Is it the number of bytes you can read from the file in text mode? (This
is likely to differ from the above on Windows systems with \r\n line
endings).
Is it the number of bytes that the UNIX "ls -l" or Windows "DIR"
command returns for that file?

What bad things will happen if the size of the file changes between
the time you compute the size of the file and the time you use that
number (for what?)?
>I couldn't find a proper way of doing it.
Depending on your definition of the size of a file, opening the
file (in binary or text mode; which mode you use may affect the
answer), and reading and counting characters will work.
>What I was planning to do is...
Open the requested file,
default position is 1st byte.
Now I use fseek() and move it till the send of the file.
Problem: a binary file need not meaningfully support seeking
to the end of the file. In CP/M, for example, the size of a
binary file is a multiple of the block size, and it doesn't
keep track of how far into the last block you've written.
>Than I use ftell() to get the current position in the file.
Problem: For a text file, the position need not be a number
of anything. It could be a bitfield of sector, head, cylinder,
track, train, disk number, etc. that has no correlation to a number
of bytes.
>this should return the num of bytes (length / size) of the file.

Is this a proper way to do?
It's not portable under ANSI C.
>Is there any efficient way to do so?
There isn't a portable, efficient way to do so. stat(), if available,
might be more efficient than your method. Opening the file, reading
it, and counting bytes may be very inefficient.

Sep 7 '08 #3
On September 7, 2008 16:04, in comp.lang.c, Gordon Burditt
(go***********@ burditt.org) wrote:
>>I 'm new to C programming and 'm stuck somewhere.
I want to find the size of a file.

First of all, you need to define what *IS* the size of a file.
It's not a trivial question.
Agreed
Is it the amount of space it takes on disk, including partially unused
blocks? Does that include the size of a directory slot? Inode?
Is it the number of bytes you can read from the file in binary mode?
Is it the number of bytes you can read from the file in text mode? (This
is likely to differ from the above on Windows systems with \r\n line
endings).
Is it the number of bytes that the UNIX "ls -l" or Windows "DIR"
command returns for that file?
Is it the count of the number of bytes stored in a sparse file (where there
are areas of the file with no data at all) or is it the "virtual" size of
the sparse file, where the intervening empty spots are presumed to have
data? (Note, at least in unix, the "ls" command shows the "virtual" size,
rather than a count of the real data written to a sparse file.)

[snip]
--
Lew Pitcher

Master Codewright & JOAT-in-training | Registered Linux User #112576
http://pitcher.digitalfreehold.ca/ | GPG public key available by request
---------- Slackware - Because I know what I'm doing. ------
Sep 7 '08 #4
Ashit Vora wrote:
Hi,
I 'm new to C programming and 'm stuck somewhere.
I want to find the size of a file.
I couldn't find a proper way of doing it.
What I was planning to do is...
Open the requested file,
default position is 1st byte.
Now I use fseek() and move it till the send of the file.
Than I use ftell() to get the current position in the file.

this should return the num of bytes (length / size) of the file.

Is this a proper way to do?
Is there any efficient way to do so?
Unfortunately, this is problematic. There are two kinds of streams,
binary and text.

7.19.9.2p3 says "A binary stream need not meaningfully support fseek
calls with a whence value of SEEK_END".

7.19.9.4p2 says, with regard to the ftell() function, that "For a
text stream, its file position indicator contains unspecified
information ...; the difference between two such return values is not
necessarily a meaningful measure of the number of characters written
or read."

Therefore, no matter what kind of stream you have, either the fseek()
or the ftell() function is, at least in principle, unreliable for this
purpose. In practice, for many implementations they will all work
exactly as you expect. However, the only reasonably portable way to do
it is to open the file in binary mode, read it a character at a time,
keep count of how many characters have been red and wait for the end
of file. Even this technique won't work if the stream that your
reading isn't really a file, but is a special device.

There are more efficient ways of finding out the file size, but the
appropriate method is different for different operating systems. On
the systems I use most frequently, the relevant function is called
stat(). It might be a very different function on your system.

Also, keep in mind that there are many different numbers that might be
described as the size of a file (the amount of size it takes up on
disk, the amount of data it contains, the compressed size, the
uncompressed size, etc.), and different operating systems may give you
access to numbers with different meanings. Also, if you're using a
file whose size might change for reasons outside of your control
during the time you're working on it, the value for the size that you
get at one time might be out-of-date by the time you actually use that
information.
Sep 7 '08 #5
Daniel Kraft wrote, On 07/09/08 20:52:
Ashit Vora wrote:
>Hi,
I 'm new to C programming and 'm stuck somewhere.
I want to find the size of a file.
I couldn't find a proper way of doing it.
What I was planning to do is...
Open the requested file,
default position is 1st byte.
Now I use fseek() and move it till the send of the file.
Than I use ftell() to get the current position in the file.

That's what I would do, too (and what I was suggested to do when I had
the same problem some time ago).
That is not a portable way to do it, and in any case it depends on what
you mean by the size of a file.
I don't know of any other way (to do it portably). There may be
"better" tricks using platform specific APIs (like POSIX) though.
I suggest both of you read question 19.12 of the comp.lang.c FAQ at
http://c-faq.com/ and the questions it links to. Also search this group
for all the long discussions about this topic. Then ask if you need
further information.
--
Flash Gordon
Sep 7 '08 #6
rio

"Gordon Burditt" <go***********@ burditt.orgha scritto nel messaggio
news:_-*************** *************** @posted.interne tamerica...
I 'm new to C programming and 'm stuck somewhere.
I want to find the size of a file.

What bad things will happen if the size of the file changes between
the time you compute the size of the file and the time you use that
number (for what?)?
easy i detect it and send an error message
something as
a=getsize(file)
if((int)a<0) goto error;
b=malloc(a+128)
if(b==0) goto error;
r=getfile(b, file, a+120)
if(r==0) /* not get all the file until EOF */
goto error;

Sep 8 '08 #7
On 2008-09-08, rio <a@b.cwrote:
>
"Gordon Burditt" <go***********@ burditt.orgha scritto nel messaggio
news:_-*************** *************** @posted.interne tamerica...
>I 'm new to C programming and 'm stuck somewhere.
I want to find the size of a file.

What bad things will happen if the size of the file changes between
the time you compute the size of the file and the time you use that
number (for what?)?

easy i detect it and send an error message
It wasn't a challenge, it was a legitimate question about your
implmentation - so not "easy" :-)
something as
Whitespace? Fixed:
a = getsize(file)
if(a < 0)
goto error;
b = malloc(a + 128)
if(b == 0)
goto error;
r = getfile(b, file, a + 120)

if(r == 0) /* not get all the file until EOF */
goto error;
Well, this code still doesn't quite make sense. Maybe if I knew
how getsize() and getfile() were defined it would.
--
Andrew Poelstra ap*******@wpsof tware.com
To email me, use the above email addresss with .com set to .net
Sep 8 '08 #8
On Mon, 8 Sep 2008 19:10:54 +0200, "rio" <a@b.cwrote:
>
"Gordon Burditt" <go***********@ burditt.orgha scritto nel messaggio
news:_-*************** *************** @posted.interne tamerica...
>I 'm new to C programming and 'm stuck somewhere.
I want to find the size of a file.

What bad things will happen if the size of the file changes between
the time you compute the size of the file and the time you use that
number (for what?)?

easy i detect it and send an error message
something as
a=getsize(file )
if((int)a<0) goto error;
What is a that you think casting it to an int will do any good?
>b=malloc(a+128 )
if(b==0) goto error;
r=getfile(b, file, a+120)
if(r==0) /* not get all the file until EOF */
goto error;

--
Remove del for email
Sep 9 '08 #9
On Mon, 08 Sep 2008 23:04:41 GMT, Andrew Poelstra
<ap*******@supe rnova.homewrote :
>On 2008-09-08, rio <a@b.cwrote:
>>
"Gordon Burditt" <go***********@ burditt.orgha scritto nel messaggio
news:_-*************** *************** @posted.interne tamerica...
>>I 'm new to C programming and 'm stuck somewhere.
I want to find the size of a file.

What bad things will happen if the size of the file changes between
the time you compute the size of the file and the time you use that
number (for what?)?

easy i detect it and send an error message

It wasn't a challenge, it was a legitimate question about your
implmentatio n - so not "easy" :-)
>something as

Whitespace? Fixed:
>a = getsize(file)
if(a < 0)
It's one thing to reformat code to make it readable but you really
should include all the code from the original post. You left out a
cast (which admittedly makes no sense but it was in the original).
> goto error;
b = malloc(a + 128)
if(b == 0)
goto error;
r = getfile(b, file, a + 120)

if(r == 0) /* not get all the file until EOF */
goto error;

Well, this code still doesn't quite make sense. Maybe if I knew
how getsize() and getfile() were defined it would.
--
Remove del for email
Sep 9 '08 #10

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

Similar topics

17
15988
by: Arnold | last post by:
Is using fseek and ftell a reliable method of getting the file size on a binary file? I thought I remember reading somewhere it wasn't... If not what would be the "right" and portable method to obtain it? Thanks.
6
2479
by: Andrew Clark | last post by:
*** post for FREE via your newsreader at post.newsfeed.com *** Hello all, I recall several threads over the years about how reading file size cannot be done consistantly or portably, but I don't remember any good reasons (not that I haven't read them, I'm sure, but it's more of a failure to hold them in my brain). Here is an attempt that I was commissioned to write, and I'd appreciate any comments and/or criticism (specific or...
8
564
by: Dave | last post by:
I am serialising an object to a memory mapped file (using the CreateFileMapping and MapViewOfFile p/invoke calls). These need to know the maximum size of the "file". I can put in a "good guess" ie it won't be more than, say, 1K, but it would be tidier to use the actaul size. Is it actually possible to find out how big an object (or even better, a class) would be when it is serialised (I suppose one way would be to separately serialise it...
8
21475
by: Ron | last post by:
Hi all, How do I determine the size of the tables I'm using? I looked under properties and it's not there. The book I just browsed said table is limited to 1GB. How do I find out what size my tables are? TIA ron
5
3733
by: Jefferis NoSpamme | last post by:
Hi all, I'm trying to limit the file size of an image submission and I keep running into various problems. I've got most of it working, but I'm stumped and I have a basic question as to WHY this works at all! if ($_FILES !="") { if ($_FILES<=0) { header("Location: /fileerror.php"); exit; }
12
15662
by: Phil Z. | last post by:
After migrating an ASP.NET 1.1 application to 2.0 we were getting "Cannot access a closed file" errors when uploading. I found a number of post on the subject and have since moved from using an Html File Input control to using the new FileUpload control. Previously, I had set the maxRequestLength attribute in the machine.config file to allow 100MB uploads with success. In the v2.0 application I have added an httpRuntime node to the...
4
3666
by: Doug | last post by:
Hi, It looks like the only way to get a size of a file within csharp is to use FileInfo and the Length property. However that only returns the number of bytes in the file which is translating properly (I have a file that has a size of 1 KB but has 14 bytes in it so the conversion isn't working right). Is there some method/property out there that will get the actual size of the file? Also, would there be a method like this that will...
1
5451
by: chrisj | last post by:
I'm using freeASPupload and got some assistance integrating to a Member script. It works successfully. In this modified version there are two groups that use this upload script. Members of one group get automatically re-directed after uploading. However, this member group never gets the benefit of knowing if they've uploaded an incorrect file size or incorrect file extension. Members from the second group do see the "exceeds max file...
18
2821
by: MisterE | last post by:
I hear that this isn't always valid: FILE *in; long size; in = fopen("foo.bar","rb"); fseek(in,0,SEEK_END); size = ftell(in); fseek(in,0,SEEK_SET); then fread size many bytes into memory.
0
8611
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,...
0
9170
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9031
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8904
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
8876
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
5867
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
4372
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2341
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
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.