0

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?

Dan D.
  • 73,243
  • 15
  • 104
  • 123
Sujoy
  • 1
  • 1
  • 2

6 Answers6

2

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

bmargulies
  • 97,814
  • 39
  • 186
  • 310
2

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.

AProgrammer
  • 51,233
  • 8
  • 91
  • 143
1

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().

Sadique
  • 22,572
  • 7
  • 65
  • 91
  • where is the definition of stat or what the body of stat contain? – Sujoy Apr 22 '11 at 16:21
  • @Sujoy:: See the edit. Btw you did not tell the size of your file by simply right-clicking on it and checking properties. – Sadique Apr 22 '11 at 16:25
0

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

user541686
  • 205,094
  • 128
  • 528
  • 886
  • _filelength doesn't work with file pointers. However you can always do this: size = _filelength(_fileno(fp)); – Tim Ring Sep 20 '12 at 10:31
0

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);
BiGYaN
  • 6,974
  • 5
  • 30
  • 43
0

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);
Angel
  • 1