How to get correct size of a text file in standard c ?

P

pninja005

How does one get the correct length of a text file in standard c ?
I know ftell() does not work due to the carriage return-linefeed
translation.

Thanks for any help !
 
R

Richard Heathfield

pninja005 said:
How does one get the correct length of a text file in standard c ?
I know ftell() does not work due to the carriage return-linefeed
translation.

There is no portable method, either for text files or for binary files,
other than reading every byte and counting as you go.

Your OS probably has an API call for this. If a non-ISO solution is
acceptable, check with a platform-specific newsgroup.
 
S

santosh

pninja005 said:
How does one get the correct length of a text file in standard c ?
I know ftell() does not work due to the carriage return-linefeed
translation.

Thanks for any help !

It's not really possible in standard C. The OS is free to store any
amount of extra bytes along with a file for it's internal purposes. And
as you note some characters may get translated by your environment.
Nearly all modern systems provide system calls to accomplish this.
Using them may be the best strategy. If you still want to do it in
standard C, as Richard notes, you need to read in the whole file and
keep count. This count is not likely to correspond exactly with the on
disk size of the file.
 
C

CBFalconer

pninja005 said:
How does one get the correct length of a text file in standard c ?
I know ftell() does not work due to the carriage return-linefeed
translation.

First you define "correct length". I can think of systems that
store text in 128 byte chunks, in reversed order by line, for good
reasons. No \n or \r in the lot.
 
R

Randy Howard

pninja005 said:


There is no portable method, either for text files or for binary files,
other than reading every byte and counting as you go.

Even that isn't reliable, as files with so-called "resource forks" as
in Mac OS file systems can be larger than reported by such a method.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top