File size: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|UNIX Shell}}: cut(1) requires only one space between fields, but ls(1) and wc(1) print too many spaces. Use tr(1) to cope. Add BSD stat(1).)
(→‎{{header|Go}}: library changes, added error checking)
Line 309: Line 309:
=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<lang go>package main

import "fmt"
import "fmt"
import "os"
import "os"

func printFileSize(f string) {
if stat, err := os.Stat(f); err != nil {
fmt.Println(err)
} else {
fmt.Println(stat.Size())
}
}


func main() {
func main() {
stat, _ := os.Stat("input.txt")
printFileSize("input.txt")
printFileSize("/input.txt")
fmt.Println(stat.Size);
stat, _ = os.Stat("/input.txt")
fmt.Println(stat.Size);
}</lang>
}</lang>



Revision as of 02:35, 3 December 2011

Task
File size
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the job is to verify the size of a file called "input.txt" for a file in the current working directory and another one in the file system root.

Ada

<lang ada>with Ada.Directories; use Ada.Directories; with Ada.Text_IO; use Ada.Text_IO;

procedure Test_File_Size is begin

  Put_Line (File_Size'Image (Size ("input.txt")) & " bytes");
  Put_Line (File_Size'Image (Size ("/input.txt")) & " bytes");

end Test_File_Size;</lang> Note that reference to the root directory, if there is any, is OS specific.

ALGOL 68

There is no build in way to find the size of an arbitrary file, especially of the file is a special channel, e.g. a tape device.

Conceptually the procedure <lang algol68>PROC set = (REF FILE file, INT page, line, character)VOID: ~ </lang> could be used to do a binary search find the last page's page number. And if it is known that every page has the same number of lines, and every line has the same number of char[s], and the character set is not compressible, then the size could be quickly calculated. Otherwise every page, and every line would have to be tallied.

It is probably much easier to use some an operating system library. This library is not part of the standard ALGOL 68 language definition.

AutoHotkey

<lang AutoHotkey>FileGetSize, FileSize, input.txt  ; Retrieve the size in bytes. MsgBox, Size of input.txt is %FileSize% bytes FileGetSize, FileSize, \input.txt, K  ; Retrieve the size in Kbytes. MsgBox, Size of \input.txt is %FileSize% Kbytes</lang>

BBC BASIC

<lang bbcbasic> file% = OPENIN(@dir$+"input.txt")

     IF file% THEN
       PRINT "File size = " ; EXT#file%
       CLOSE #file%
     ENDIF
     
     file% = OPENIN("\input.txt")
     IF file% THEN
       PRINT "File size = " ; EXT#file%
       CLOSE #file%
     ENDIF</lang>

C

<lang c>#include <stdlib.h>

  1. include <stdio.h>

long getFileSize(const char *filename) {

 long result;
 FILE *fh = fopen(filename, "rb");
 fseek(fh, 0, SEEK_END);
 result = ftell(fh);
 fclose(fh);
 return result;

}

int main(void) {

 printf("%ld\n", getFileSize("input.txt"));
 printf("%ld\n", getFileSize("/input.txt"));
 return 0;

}</lang>

Works with: POSIX

<lang c>#include <stdlib.h>

  1. include <stdio.h>
  2. include <sys/stat.h>

int main(void) {

 struct stat foo;
 stat("input.txt", &foo);
 printf("%ld\n", foo.st_size);
 stat("/input.txt", &foo);
 printf("%ld\n", foo.st_size);
 return 0;

}</lang>

C++

<lang cpp>#include <iostream>

  1. include <fstream>

std::ios::off_type getFileSize(const char *filename) {

 std::ifstream f(filename);
 std::ios::pos_type begin = f.tellg();
 f.seekg(0, std::ios::end);
 std::ios::pos_type end = f.tellg();
 return end - begin;

}

int main() {

 std::cout << getFileSize("input.txt") << std::endl;
 std::cout << getFileSize("/input.txt") << std::endl;
 return 0;

}</lang>

C#

<lang csharp>using System; using System.IO;

class Program {

   static void Main(string[] args)
   {
       Console.WriteLine(new FileInfo("/input.txt").Length);
       Console.WriteLine(new FileInfo("input.txt").Length);
   }

} </lang>

Clean

There is not function to get the file size, therefore we seek to the end and query the file pointer position.

<lang clean>import StdEnv

fileSize fileName world

   # (ok, file, world) = fopen fileName FReadData world
   | not ok = abort "Cannot open file"
   # (ok, file) = fseek file 0 FSeekEnd
   | not ok = abort "Cannot seek file"
   # (size, file) = fposition file
     (_, world) = fclose file world
   = (size, world)

Start world = fileSize "input.txt" world</lang>

Clojure

<lang clojure>(import '[java.io File]) (defn show-size [filename]

 (println filename "size:" (.length (File. filename))))

(show-size "input.txt") (show-size "/input.txt")</lang>

ColdFusion

<lang ColdFusion><cfscript>

 localFile = getFileInfo(expandpath("input.txt"));
 rootFile = getFileInfo("/input.txt");

</cfscript>

<cfoutput>

 Size of input.txt is #localFile.size# bytes.
 Size of /input.txt is #rootFile.size# bytes.

</cfoutput></lang>

Common Lisp

<lang lisp>(with-open-file (stream (make-pathname :name "input.txt")

                :direction :input
                :if-does-not-exist nil)
 (print (if stream (file-length stream) 0)))
 

(with-open-file (stream (make-pathname :directory '(:absolute "") :name "input.txt")

                :direction :input
                :if-does-not-exist nil)
 (print (if stream (file-length stream) 0)))</lang>

D

To gets the size of a single file: <lang d>import std.file;

void main() {

   auto len = getSize("data.txt");

}</lang> Alternative ways to get file sizes: <lang d>import std.stdio, std.path, std.file, std.stream; // NB: mmfile can treat the file as an array in memory import std.mmfile;

string[] generateTwoNames(string name) {

   string cwd  = curdir ~ sep; // on current directory
   string root = sep;          // on root
   // remove path, left only basename
   name = std.path.getBaseName(name);
   // NB: in D ver.2, getBaseName is alias of basename
   return [cwd ~ name, root ~ name];

}

void testsize(string fileName1) {

   foreach (fileName2; generateTwoNames(fileName1)) {
       try {
           writefln("File %s has size:", fileName2);
           writefln("%10d bytes by std.file.getSize (function),",
                    std.file.getSize(fileName2));
           writefln("%10d bytes by std.stream (class),",
                    (new std.stream.File(fileName2)).size);
           writefln("%10d bytes by std.mmfile (class).",
                    (new std.mmfile.MmFile(fileName2)).length);
       } catch (Exception e) {
           writefln(e.msg);
       }
       writeln();
   }

}

void main() {

   testsize(r"input.txt");

}</lang> One output:

File .\input.txt has size:
    749596 bytes by std.file.getSize (function),
    749596 bytes by std.stream (class),
    749596 bytes by std.mmfile (class).

File \input.txt has size:
    471964 bytes by std.file.getSize (function),
    471964 bytes by std.stream (class),
    471964 bytes by std.mmfile (class).

Delphi

<lang Delphi>program SizeOfFile;

{$APPTYPE CONSOLE}

uses SysUtils;

function CheckFileSize(const aFilename: string): Integer; var

 lFile: file of Byte;

begin

 AssignFile(lFile, aFilename);
 FileMode := 0; {Access file in read only mode}
 Reset(lFile);
 Result := FileSize(lFile);
 CloseFile(lFile);

end;

begin

 Writeln('input.txt ' + IntToStr(CheckFileSize('input.txt')));
 Writeln('\input.txt ' + IntToStr(CheckFileSize('\input.txt')));

end.</lang>

E

<lang e>for file in [<file:input.txt>, <file:///input.txt>] {

 println(`The size of $file is ${file.length()} bytes.`)

}</lang>

Erlang

<lang erlang>-module(file_size). -export([file_size/0]).

-include_lib("kernel/include/file.hrl").

file_size() ->

   print_file_size("input.txt"),
   print_file_size("/input.txt").

print_file_size(Filename) ->

   case file:read_file_info(Filename) of

{ok, FileInfo} -> io:format("~s ~p~n", [Filename, FileInfo#file_info.size]); {error, _} -> io:format("~s could not be opened~n",[Filename])

   end.

</lang>


Euphoria

<lang euphoria>include file.e

function file_size(sequence file_name)

   object x
   x = dir(file_name)
   if sequence(x) and length(x) = 1 then
       return x[1][D_SIZE]
   else
       return -1 -- the file does not exist
   end if

end function

procedure test(sequence file_name)

   integer size
   size = file_size(file_name)
   if size < 0 then
       printf(1,"%s file does not exist.\n",{file_name})
   else
       printf(1,"%s size is %d.\n",{file_name,size})
   end if

end procedure

test("input.txt") -- in the current working directory test("/input.txt") -- in the file system root</lang>

Factor

<lang factor>"input.txt" file-info size>> .

   1321

"file-does-not-exist.txt" file-info size>>

"Unix system call ``stat failed:"...</lang>

Forth

<lang forth>: .filesize ( addr len -- ) 2dup type ." is "

 r/o open-file throw
 dup file-size throw  <# #s #> type ."  bytes long." cr
 close-file throw ;
s" input.txt" .filesize

s" /input.txt" .filesize</lang>

Go

<lang go>package main

import "fmt" import "os"

func printFileSize(f string) {

   if stat, err := os.Stat(f); err != nil {
       fmt.Println(err)
   } else {
       fmt.Println(stat.Size())
   }

}

func main() {

   printFileSize("input.txt")
   printFileSize("/input.txt")

}</lang>

Groovy

<lang groovy>println new File('index.txt').length(); println new File('/index.txt').length();</lang>

Haskell

<lang haskell>import System.IO

printFileSize filename = withFile filename ReadMode hFileSize >>= print

main = mapM_ printFileSize ["input.txt", "/input.txt"]</lang> or <lang haskell>import System.Posix.File

printFileSize filename = do stat <- getFileStatus filename

                           print (fileSize stat)

main = mapM_ printFileSize ["input.txt", "/input.txt"]</lang>

HicEst

<lang hicest>READ(FILE="input.txt", LENgth=bytes) ! bytes = -1 if not existent READ(FILE="C:\input.txt", LENgth=bytes) ! bytes = -1 if not existent </lang>

Icon and Unicon

Icon doesn't support 'stat'; however, information can be obtained by use of the system function to access command line. <lang Unicon>every dir := !["./","/"] do {

  write("Size of ",f := dir || "input.txt"," = ",stat(f).size)  |stop("failure for to stat ",f) 
  }</lang>

Note: Icon and Unicon accept both / and \ for directory separators.

J

<lang J>require 'files' fsize 'input.txt';'/input.txt'</lang>

Java

<lang java>import java.util.File; public class FileSizeTest {

public static long getFileSize(String filename)
{
 return new File(filename).length();
}
public static void test(String type, String filename)
{
 System.out.println("The following " + type + " called " + filename + 
          " has a file size of " + getFileSize(filename) + " bytes.");
}
public static void main(String args[])
{
 test("file", "input.txt");
 test("file", File.separator + "input.txt");
}

}</lang>

JavaScript

Works with: JScript

<lang javascript>var fso = new ActiveXObject("Scripting.FileSystemObject"); fso.GetFile('input.txt').Size; fso.GetFile('c:/input.txt').Size;</lang>

Liberty BASIC

<lang lb>'input.txt in current directory OPEN DefaultDir$ + "/input.txt" FOR input AS #m PRINT "File size: "; lof(#m) CLOSE #m

'input.txt in root OPEN "c:/input.txt" FOR input AS #m PRINT "File size: "; lof(#m) CLOSE #m</lang>

Lua

<lang Lua>function GetFileSize( filename )

   local fp = io.open( filename )
   if fp == nil then 
	return nil 
   end
   local filesize = fp:seek( "end" )
   fp:close()
   return filesize

end</lang>

Mathematica

<lang Mathematica> FileByteCount["input.txt"] FileByteCount[FileNameJoin[{$RootDirectory, "input.txt"}]]</lang>

MATLAB

<lang matlab>d1 = dir('input.txt'); d2 = dir('/input.txt'); fprintf('Size of input.txt is %d bytes\n', d1.bytes) fprintf('Size of /input.txt is %d bytes\n', d2.bytes)</lang>

MAXScript

<lang maxscript>-- Returns filesize in bytes or 0 if the file is missing getFileSize "index.txt" getFileSize "\index.txt"</lang>

Mirah

<lang mirah>import java.io.File

puts File.new('file-size.mirah').length() puts File.new("./#{File.separator}file-size.mirah").length()</lang>

Modula-3

<lang modula3>MODULE FSize EXPORTS Main;

IMPORT IO, Fmt, FS, File, OSError;

VAR fstat: File.Status;

BEGIN

 TRY
   fstat := FS.Status("input.txt");
   IO.Put("Size of input.txt: " & Fmt.LongInt(fstat.size) & "\n");
   fstat := FS.Status("/input.txt");
   IO.Put("Size of /input.txt: " & Fmt.LongInt(fstat.size) & "\n");
 EXCEPT
 | OSError.E => IO.Put("ERROR: Could not get file status.\n");
 END;

END FSize.</lang>

Objective-C

<lang objc>NSFileManager *fm = [NSFileManager defaultManager];

// Pre-OS X 10.5 NSLog(@"%llu", [[fm fileAttributesAtPath:@"input.txt" traverseLink:YES] fileSize]);

// OS X 10.5+ NSLog(@"%llu", [[fm attributesOfItemAtPath:@"input.txt" error:NULL] fileSize]);</lang>

Objeck

<lang objeck> use IO; ... File("input.txt")->Size()->PrintLine(); File("c:\input.txt")->Size()->PrintLine(); </lang>

OCaml

<lang ocaml>let printFileSize filename =

 let ic = open_in filename in
 Printf.printf "%d\n" (in_channel_length ic);
 close_in ic ;;

printFileSize "input.txt" ;; printFileSize "/input.txt" ;;</lang>

For files greater than Pervasives.max_int, one can use the module Unix.LargeFile: <lang ocaml>let printLargeFileSize filename =

 let ic = open_in filename in
 Printf.printf "%Ld\n" (LargeFile.in_channel_length ic);
 close_in ic ;;</lang>

Alternatively: <lang ocaml>#load "unix.cma" ;; open Unix ;; Printf.printf "%d\n" (stat "input.txt").st_size ;; Printf.printf "%d\n" (stat "/input.txt").st_size ;;</lang>

Oz

<lang oz>declare

 [Path] = {Module.link ['x-oz://system/os/Path.ozf']}

in

 {Show {Path.size "input.txt"}}
 {Show {Path.size "/input.txt"}}</lang>

Pascal

See Delphi

Perl

<lang perl>use File::Spec::Functions qw(catfile rootdir); print -s 'input.txt'; print -s catfile rootdir, 'input.txt';</lang>

Perl 6

<lang perl6>say 'input.txt'.IO.s; say '/input.txt'.IO.s;</lang>

PHP

<lang php><?php echo filesize('input.txt'), "\n"; echo filesize('/input.txt'), "\n"; ?></lang>

PicoLisp

<lang PicoLisp>(println (car (info "input.txt"))) (println (car (info "/input.txt")))</lang>

Pike

<lang pike>import Stdio;

int main(){

  write(file_size("input.txt") + "\n");
  write(file_size("/input.txt") + "\n");

}</lang>

Pop11

<lang pop11>;;; prints file size in bytes sysfilesize('input.txt') => sysfilesize('/input.txt') =></lang>

PostScript

status returns status information about a file if given a file name. This includes the size in pages (implementation-dependent), the size in bytes, creation and modification time and a final true. The values not needed here are simply poped off the stack. <lang postscript>(input.txt ) print (input.txt) status pop pop pop = pop (/input.txt ) print (/input.txt) status pop pop pop = pop</lang>

PowerShell

<lang powershell>Get-ChildItem input.txt | Select-Object Name,Length Get-ChildItem \input.txt | Select-Object Name,Length</lang>

PureBasic

<lang purebasic>Debug FileSize("input.txt") Debug FileSize("/input.txt")</lang>

Python

<lang python>import os

size = os.path.getsize('input.txt') size = os.path.getsize('/input.txt')</lang>

R

Works with: R version 2.8.1

R has a function file.info() in the base package that performs this function. Note that regardless of the OS, R uses forward slashes for the directories.

<lang R>sizeinwd <- file.info('input.txt')"size" sizeinroot <- file.info('/input.txt')"size"</lang>

REBOL

<lang REBOL>size? %info.txt size? %/info.txt size? ftp://username:password@ftp.site.com/info.txt size? http://rosettacode.org</lang>

RapidQ

File I/O is one of the things where RapidQ differs from standard Basic. RapidQ uses file streams.

Method 1: display file size using file streams

<lang rapidq>$INCLUDE "rapidq.inc"

DIM file AS QFileStream

FUNCTION fileSize(name$) AS Integer

   file.Open(name$, fmOpenRead)
   Result = file.Size
   file.Close

END FUNCTION

PRINT "Size of input.txt is "; fileSize("input.txt") PRINT "Size of \input.txt is "; fileSize("\input.txt")</lang>

Method 2: using DIR$

<lang rapidq>FileName$ = DIR$("input.txt", 0) PRINT "Size of input.txt is "; FileRec.Size FileName$ = DIR$("\input.txt", 0) PRINT "Size of \input.txt is "; FileRec.Size</lang>

Raven

<lang raven>'input.txt' status.size '/input.txt' status.size</lang>

Retro

The simple way is to open and read the size. This may crash if the file does not exist.

<lang Retro>with files' "input.txt" :R open &size sip close drop putn "/input.txt" :R open &size sip close drop putn</lang>

For added stability, check that the returned file handle is not zero:

<lang Retro>with files' "input.txt" :R open over 0 <> [ &size sip close drop ] ifTrue</lang>

Or, if you need to do this more often, setup a function that'll also display an error message if the file does not exist:

<lang Retro>with files'

getFileSize ( $-n )
 :R open 0 over =
 [ "File does Not Exist\n" puts ]
 [ &size sip close drop ] if ;

"input.txt" getFileSize putn "/input.txt" getFileSize putn</lang>

Ruby

<lang ruby>size = File.size('input.txt') size = File.size('/input.txt')</lang>

Scheme

<lang scheme> (define (file-size filename)

 (call-with-input-file filename (lambda (port)
   (let loop ((c (read-char port))
              (count 0))
     (if (eof-object? c) 
         count
         (loop (read-char port) (+ 1 count)))))))

(file-size "input.txt") (file-size "/input.txt") </lang>

Seed7

<lang seed7>$ include "seed7_05.s7i";

const proc: main is func

 begin
   writeln(fileSize("input.txt"));
   writeln(fileSize("/input.txt"));
 end func;</lang>

Slate

<lang slate>(File newNamed: 'input.txt') fileInfo fileSize. (File newNamed: '/input.txt') fileInfo fileSize.</lang>

Smalltalk

<lang smalltalk>(File name: 'input.txt') size printNl. (File name: '/input.txt') size printNl.</lang>

Standard ML

<lang sml>val size = OS.FileSys.fileSize "input.txt" ;; val size = OS.FileSys.fileSize "/input.txt" ;</lang>

Tcl

<lang tcl>file size input.txt file size /input.txt</lang>

Toka

A trivial method follows:

<lang toka>" input.txt" "R" file.open dup file.size . file.close " /input.txt" "R" file.open dup file.size . file.close</lang>

A better method would be to define a new function that actually checks whether the file exists:

<lang toka>[ "R" file.open

 dup 0 <> [ dup file.size . file.close ] ifTrue
 drop

] is display-size

" input.txt" display-size " /input.txt" display-size</lang>

TUSCRIPT

<lang tuscript> $$ MODE TUSCRIPT -- size of file input.txt file="input.txt" ERROR/STOP OPEN (file,READ,-std-) file_size=BYTES ("input.txt") ERROR/STOP CLOSE (file)

-- size of file x:/input.txt ERROR/STOP OPEN (file,READ,x) file_size=BYTES (file) ERROR/STOP CLOSE (file) </lang>

UNIX Shell

An interactive user would run ls -l input.txt /input.txt to see the file sizes. This task is more difficult for a shell script, that must extract each size from command output.

Using ls

ls most likely gets the length from the file's inode.

<lang bash>size1=$(ls -l input.txt | tr -s ' ' | cut -d ' ' -f 5) size2=$(ls -l /input.txt | tr -s ' ' | cut -d ' ' -f 5)</lang>

ls -l reports the size in 5th field, with spaces between fields. tr squeezes spaces (because cut needs one single space between fields), and cut extracts 5th field.

Using wc

wc may actually read the whole file and count the bytes. Some implementations, like wc.c from GNU coreutils, can optimize wc -c by getting the length from the file's inode.

<lang bash>size1=$(wc -c < input.txt | tr -d ' ') size2=$(wc -c < /input.txt | tr -d ' ')</lang>

The peculiar use of wc -c < file, not wc -c file, is to prevent printing the file's name. Then wc only reports the size. Some versions of wc print spaces before the number; tr deletes all these spaces.

Using BSD stat

BSD has stat(1), a nonstandard command. With stat, a shell script can easily get the file size.

Works with: NetBSD version 1.6
Works with: FreeBSD version 4.10
Works with: OpenBSD version 3.8

<lang bash>size1=$(stat -f %z input.txt) size2=$(stat -f %z /input.txt)</lang>

Vedit macro language

<lang vedit>Num_Type(File_Size("input.txt")) Num_Type(File_Size("/input.txt"))</lang>

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+

<lang vbnet>Dim local As New IO.FileInfo("input.txt") Console.WriteLine(local.Length)

Dim root As New IO.FileInfo("\input.txt") Console.WriteLine(root.Length)</lang>