Sujoy
Sujoy

Reputation: 1

file size in c program

I just want to find the file size with the help of c program..I wrote a code but it give wrong result...

fseek(fp,0,SEEK_END);
osize=ftell(fp);

Is there any other way?

Upvotes: 0

Views: 3193

Answers (6)

Angel
Angel

Reputation: 1

The only negative return value by ftell is -1L if an error occurs. If you don't mind using WinAPI, get file size with GetFileSizeEx:

HANDLE hFile = CreateFile(filename, 
                          GENERIC_READ,
                          0, 
                          NULL,
                          OPEN_EXISTING, 
                          FILE_ATTRIBUTE_NORMAL, 
                          NULL);

LARGE_INTEGER size;
GetFileSizeEx(hFile, &size);
printf("%ld", size.QuadPart);

CloseHandle(hFile);

Upvotes: 0

AProgrammer
AProgrammer

Reputation: 52294

ftell returns an int. If you are on a system where int is 32 bits and your file is more than 2GB, you may very well end up with a negative size. POSIX provides ftello and fseeko which use a off_t. C has fgetpos and fsetpos which use a fpos_t -- but fpos_t is not an arithmetic type -- it keeps things related to the handling of charset by the locale for instance.

Upvotes: 2

Sadique
Sadique

Reputation: 22821

There is no reason why it should not work.

Is there any other way? You can use stat, if you know the filename:

struct stat st;
stat(filename, &st);
size = st.st_size;

By the way ftell returns a long int

The sys/stat.h header defines the structure of the data returned by the functions fstat(), lstat(), and stat().

Upvotes: 1

BiGYaN
BiGYaN

Reputation: 7159

Try this using fstat():

int file=0;
if((file=open(<filename>,O_RDONLY)) < -1)
    return -1; // some error with open()

struct stat fileStat;
if(fstat(file,&fileStat) < 0)    
    return -1; // some error with fstat()

printf("File Size: %d bytes\n",fileStat.st_size);

Upvotes: 0

user541686
user541686

Reputation: 210505

Try using _filelength. It's not portable, though... I don't think there's any completely portable way to do this.

Upvotes: 0

bmargulies
bmargulies

Reputation: 100040

The stat system call is the usual solution to this problem. Or, in your particular case, fstat.

Upvotes: 2

Related Questions