Logo

Programming-Idioms

  • C
  • Java
  • PHP
  • Python

Idiom #95 Get file size

Assign to variable x the length (number of bytes) of the local file at path.

import os
x = os.path.getsize(path)
#include <stdio.h>
FILE *f = fopen(path, "rb");
fseek(f, 0, SEEK_END);
int x = ftell(f);
fclose(f);

SEEK_END isn't necessarily supported by all implementations of stdio.h, but I've never run into a problem with it.
#include <sys/stat.h>
struct stat st;
if (stat (path &st) == 0) x = st.st_size;

POSIX function stat avoids opening the file
import java.io.File;
long x = new File(path).length();
$x = filesize($path);
with Ada.Directories; use Ada.Directories;
X : constant File_Size := Size (Path);

New implementation...
< >
programming-idioms.org