Determine the size of a file

From CodeCodex

Revision as of 07:05, 24 March 2012 by 187.133.49.226 (Talk)

Implementations

Bash

$ FILESIZE=`wc -c filename`

C

#include <stdio.h>  
#include <sys/stat.h>
#include <sys/types.h>
long long getFilesize(const char *filename)  
{  FILE *FileToCheck;  
   struct stat64 FileStats;
   long long filesize;
   FileToCheck = fopen(filename, "rb");  
   fstat64(fileno(FileToCheck), &FileStats);
   filesize = FileStats.st_size;
   fclose(FileToCheck);  
   return FileStats.st_size;  }

Please note: On 32-bit OSes this program must be compiled with -D_LARGEFILE64_SOURCE. This is because this program uses the large-file extensions, which use 64-bit file handling functions. You can use the plain vanilla fstat function, which uses 32-bit numbers, but this will limit you to files smaller than 2 GB. More information on http://www.mkssoftware.com/docs/man5/lfcompile.5.asp

It is also possible to use a standard filename instead of a file descriptor by using the stat/stat64 function instead; this example uses fstat64 for demonstrational purposes.

Common Lisp

(with-open-file (file "filename") (file-length file))

Erlang

filelib:file_size(Filename).

Java

    File file = new File("infilename");
    
    // Get the number of bytes in the file
    long length = file.length();

Perl

my $file_size = -s 'filename';

PHP

$file_size = filesize('filename');

Python

TheFileSize = os.path.getsize(TheFileName)

Ruby

size = File.size(file_name)

Seed7

size := fileSize(file_name);

Tcl

proc filesize f {
  file stat $f a
  return $a(size)
}

Zsh

zmodload -i zsh/stat
zstat +size filename