This language bar is your friend. Select your favorite languages!

Idiom #95 Get file size

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

def file_size(path)
  "stat -f%z #{path}"
end
x = File.size(path)
#include <stdio.h>
FILE *f = fopen(path, "rb");
fseek(f, 0, SEEK_END);
int x = ftell(f);
#include <sys/stat.h>
struct stat st;
if (stat (path, &st) == 0) x = st.st_size;
#include <fstream>
std::ifstream f(path, std::ios::in | std::ios::binary);
f.seekg(0, std::ios::end);
size_t x = f.tellg();
using System.IO
var filePath = "Sample.txt";
var fileInfo = new FileInfo(filePath);
var _x = fileInfo.Length;

import std.file: getSize;
auto x = getSize(path);
program xx
implicit none
character(len=256) :: message
character(len=4096) :: filename
integer :: ios,x
logical :: foundit
filename='myfile'
inquire(file=filename,exist=foundit,size=x,iostat=ios,iomsg=message)
if(.not.foundit)then
   write(*,*)'file ',trim(filename),' not found'
elseif(ios.ne.0)then
   write(*,*)trim(message)
else
   write(*,*)'size =',x,'bytes'
endif
end program xx
import "os"
f, err := os.Open(path)
defer f.Close()
if err != nil {
	return err
}
info, err := f.Stat()
if err != nil {
	return err
}
x := info.Size()
import System.IO
fileSize :: FilePath -> IO Integer
fileSize path = withFile path ReadMode hFileSize
const {readFileSync: read} = require ('fs')
let x = read(path).length
import java.io.File;
long x = new File(path).length();
$x = filesize($path);
uses fileutil;
x := filesize(path);
my $x = -s $path;
import os
x = os.path.getsize(path)
use std::fs;
let x = fs::metadata(path)?.len();

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org