Difference between revisions of "Determine the size of a file"

From CodeCodex

(C)
 
Line 2: Line 2:
 
===Bash===
 
===Bash===
 
<pre>
 
<pre>
$ FILESIZE=`wc -c filename`
+
$ wc -c filename
 
</pre>
 
</pre>
  
 
===C===
 
===C===
 
<pre class="c">
 
<pre class="c">
#include <stdio.h>
+
#include <stdio.h>
#include <sys/stat.h>
+
int main()
#include <sys/types.h>
+
{  FILE *FileToCheck;
long long getFilesize(const char *filename)
+
   long filesize;
{  FILE *FileToCheck;
+
   FileToCheck = fopen("filename", "rb");
   struct stat64 FileStats;
+
   fseek(FileToCheck, 0, SEEK_END);
  long long filesize;
+
   filesize = ftell(FileToCheck);
   FileToCheck = fopen(filename, "rb");
+
   fclose(FileToCheck);
   fstat64(fileno(FileToCheck), &FileStats);
+
   return 0;  }
   filesize = FileStats.st_size;
+
   fclose(FileToCheck);
+
   return FileStats.st_size;  }
+
 
</pre>
 
</pre>
'''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===
 
===Common Lisp===

Latest revision as of 22:36, 25 March 2012

Implementations[edit]

Bash[edit]

$ wc -c filename

C[edit]

#include <stdio.h>
int main()
{  FILE *FileToCheck;
   long filesize;
   FileToCheck = fopen("filename", "rb");
   fseek(FileToCheck, 0, SEEK_END);
   filesize = ftell(FileToCheck);
   fclose(FileToCheck);
   return 0;  }

Common Lisp[edit]

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

Erlang[edit]

filelib:file_size(Filename).

Java[edit]

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

Perl[edit]

my $file_size = -s 'filename';

PHP[edit]

$file_size = filesize('filename');

Python[edit]

TheFileSize = os.path.getsize(TheFileName)

Ruby[edit]

size = File.size(file_name)

Seed7[edit]

size := fileSize(file_name);

Tcl[edit]

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

Zsh[edit]

zmodload -i zsh/stat
zstat +size filename