Logo

Programming-Idioms

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.

use std::fs;
let x = fs::metadata(path)?.len();
use std::fs;
use std::io;
use std::os::linux::fs::MetadataExt;
let x = fs::metadata(path)?.st_size();
use std::path::Path;
let x = path.metadata()?.len();
with Ada.Directories; use Ada.Directories;
X : constant File_Size := Size (Path);
#include <stdio.h>
FILE *f = fopen(path, "rb");
fseek(f, 0, SEEK_END);
int x = ftell(f);
fclose(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;
long? FileSize(string path) {
    if (!File.Exists(path)) {
        return null;
    }
    return (new FileInfo(filePath)).Length;
}
using System.IO
var filePath = "Sample.txt";
var fileInfo = new FileInfo(filePath);
var _x = fileInfo.Length;

import std.file: getSize;
auto x = getSize(path);
import 'dart:io';
final x = (await File(path).readAsBytes()).length;
var x = File(path).lengthSync();
def main(path) do
  _x =
    path
    |> File.stat!()
    |> Map.get(:size)
end
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"
info, err := os.Stat(path)
if err != nil {
	return err
}
x := info.Size()
import System.IO
filesize = withFile path ReadMode hFileSize
const {readFileSync: read} = require ('fs')
let x = read(path).length
import java.io.File;
long x = new File(path).length();
(ql:quickload :osicat)
(defvar x (osicat-posix:stat-size (osicat-posix:stat #P"path")))
$x = filesize($path);
uses fileutil;
x := filesize(path);
my $x = -s $path;
import os
x = os.path.getsize(path)
x = File.size(path)

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