By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,819 Members | 1,185 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,819 IT Pros & Developers. It's quick & easy.

Calculating File Size in C

seeminsuleri
P: 9
hello there,
Can anyone plz guide me how to calculate the sise of a string present in an opened file.
we already have the file descriptor, inputFile. but when i try to do

begin=inputFile.tellg();
inputFile.seekg(0,ios::end);
end=inputFile.tellg();
size=end-begin;

it doesnt work in C. It does work in C++ though.
Can u plz give me some C alternative for the above.
Nov 3 '06 #1
Share this Question
Share on Google+
5 Replies


100+
P: 145
Well, a primative but sure-fire way to get the job done is to read bytes (or some other data size) until you reach the end, and keep track. All the traditional FILE operations still go in C, right? e.g.,

int count = 0;
FILE* fp;
fp = fopen( "file.txt", "r" );

while( !feof( fp ) && fp )
{
unsigned char c;
fread( &c , 1,1, fp );
count++;
}
if( fp )
{ fclose( fp ); }


Again, not elegant, but robust. :) -- Paul
Nov 3 '06 #2

seeminsuleri
P: 9
thanks for your help Paul,
I was looking at a code

fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);

I didnt know these functions exist in C.
I think they would do the job too.

Well, a primative but sure-fire way to get the job done is to read bytes (or some other data size) until you reach the end, and keep track. All the traditional FILE operations still go in C, right? e.g.,

int count = 0;
FILE* fp;
fp = fopen( "file.txt", "r" );

while( !feof( fp ) && fp )
{
unsigned char c;
fread( &c , 1,1, fp );
count++;
}
if( fp )
{ fclose( fp ); }


Again, not elegant, but robust. :) -- Paul
Nov 4 '06 #3

100+
P: 145
thanks for your help Paul,
I was looking at a code

fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);

I didnt know these functions exist in C.
I think they would do the job too.
Ah, that's much more elegant, and likely more efficient, too. Nice work. :) -- Paul
Nov 4 '06 #4

P: 9
there is an another function
filelength(int fd); which returns the length of the file associated with the handle fd.
U need to include io.h b4 using this function.
Nov 4 '06 #5

P: 1
About the fseek - ftell method, I should add that I saw this on http://www.cplusplus.com/reference/clibrary/cstdio/ftell.html

"For text streams, the value is not guaranteed to be the exact number of bytes from the beginning of the file, but the value returned can still be used to restore the position indicator to this position using fseek."

Thus, the value is not guaranteed. So you might want to consider a different method for calculating length of string files.
May 22 '08 #6

Post your reply

Sign in to post your reply or Sign up for a free account.