Filesizes in C
I''m having the following code in one of my functions :
FILE *file;
file=fopen(filename,"rb");
Now my problem, in my reference book I found nothing about getting the filesize of the given file.
Can anybody help me?
Everything is possible ...
... at least I think so.
you could use the unix way:
or the windows way:
#include
...
struct stat sb;
stat (filename,&sb)
printf("File size is: %d\n",sb.st_size);
or the windows way:
#include <windows.h>
...
HANDLE h = CreateFile( ... )
DWORD highDWord, lowDWord;
lowDWord = GetFileSize(h, &highDWord);
printf("filesize is: %d\n", lowDWord); // fails for files > 4gig
or the "stdio" way:
#include <stdio.h>
FILE *fh = fopen(fn,"rb");
int old_pos = ftell(fh);
lseek(fh,0,SEEK_END);
long pos = ftell(fh);
printf("filesize is: %d\n", pos);
fseek(fh,old_pos,SEEK_SET);
Hope that helps...
-- Pryankster
(Check out my game, a work in progress: DigiBot)
Edited by - Pryankster on June 4, 2000 1:12:45 PM
-- Pryankster(Check out my game, a work in progress: DigiBot)
The stdio way is slightly wrong. ftell() returns a long, not an int. I also recommend using fseek() instead of lseek(), since fseek() is ANSI compatible, which lseek() isn't. This is how it should be:
/. Muzzafarath
Mad House Software
Edited by - Muzzafarath on June 4, 2000 1:44:09 PM
Edited by - Muzzafarath on June 4, 2000 1:45:16 PM
#include < stdio.h>
FILE *fh = fopen(fn,"rb");
long old_pos = ftell(fh);
fseek(fh,0,SEEK_END);
long pos = ftell(fh);
printf("Filesize is: %ld\n", pos);
fseek(fh,old_pos,SEEK_SET);
/. Muzzafarath
Mad House Software
Edited by - Muzzafarath on June 4, 2000 1:44:09 PM
Edited by - Muzzafarath on June 4, 2000 1:45:16 PM
I'm reminded of the day my daughter came in, looked over my shoulder at some Perl 4 code, and said, "What is that, swearing?" - Larry Wall
There is a small problem, nobody here is checking the return value of "fopen()". By not checking it you risk using a NULL pointer!
This is a better way to use "fopen()".
FILE *fp;
if((fp=fopen(filename, "r+b"))!=NULL) {
rewind(fp);
//do other stuff here
fclose(fp);
}
else {
//display error messages
}
This is a better way to use "fopen()".
FILE *fp;
if((fp=fopen(filename, "r+b"))!=NULL) {
rewind(fp);
//do other stuff here
fclose(fp);
}
else {
//display error messages
}
http://www.crosswinds.net/~druidgames/resist.jpg
Bah. You''re right ... fseek, not lseek (blame it on all those years using file-descriptor I/O on unix, instead of stdio ;-)
And I forgot to add "error checking elided for clarity" ;-)
And I forgot to add "error checking elided for clarity" ;-)
-- Pryankster(Check out my game, a work in progress: DigiBot)
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement