Today, once again, we are going to exercise our knowledge by creating routines that can be useful in different situations. And this time we will see how to know the size of a file in 10 different programming languages, they are: C , C++ , Java , C# , [PHP] (https://terminalroot.com/tags#php), Lua , Perl , Python , JavaScript /Node.js and Go/Golang .
As in the article:
I’ll just post the code for each of them!
The file.iso
file is fictitious and you must replace it with a valid file on your computer to carry out the tests.
You can compare the result using the command: du -h file.iso
.
01. C
filesize.c
#include <stdio.h>
int main (){
FILE * file = fopen ( "file.iso" , "rb" );
fseek ( file , 0 , SEEK_END );
int size = ftell ( file );
fclose ( file );
printf ( "%d MB \n " , ( size / 1024 ) / 1024 );
return 0 ;
}
gcc filesize.c && ./a.out
filesize.cpp
#include <iostream>
#include <fstream>
int main (){
std :: ifstream file ( "file.iso" , std :: ios :: in | std :: ios :: binary );
file . seekg ( 0 , std :: ios :: end );
std :: cout << ( file . tellg () / 1024 ) / 1024 << " MB \n " ;
return 0 ;
}
g++ filesize.cpp && ./a.out
FileSize.java
import java.io.File ;
public class FileSize {
public static void main ( String [] args ) {
String path = "file.iso" ;
long size = new File ( path ). length ();
System . out . println (( size / 1024 ) / 1024 + " MB" );
}
}
javac FileSize.java && java FileSize
filesize.lua
file = io.open ( "file.iso" , "r" )
size = math.floor (( file : seek ( "end" ) / 1024 ) / 1024 )
print ( size .. " MB" )
lua filesize.lua
filesize.pl
$path = " file.iso ";
my $x = - s $path;
$x = ($x / 1024) / 1024 ;
$x = int ( $x );
print (" $x MiB \n ");
perl filesize.pl
filesize.py
import os
path = "file.iso"
size = os . path . getsize ( path )
print ( str ( int ( ( size / 1024 ) / 1024 ) ) + " MB" )
python filesize.py
filesize.php
<?php
$path = "file.iso" ;
$x = filesize ( $path ) / 1024 / 1024 ;
echo intval ( $x ) . " MB \n " ;
php filesize.php
dotnet new console -o FileSize && cd FileSize && vim Program.cs
string path = "file.iso" ;
long size = new System . IO . FileInfo ( path ). Length ;
Console . WriteLine ( ( size / 1024 ) / 1024 + " MB" );
dotnet run
filesize.js
const { readFileSync: read } = require ( 'fs' )
const path = "file.iso"
let size = read ( path) .length
size = ( size / 1024) / 1024
console.log( parseInt( size) + " MB" )
node filesize.js
filesize.go
package main
import ( "fmt" ; "os" )
func main (){
file , err := os . Stat ( "file.iso" )
_ = err
size := file . Size ()
fmt . Println ( ( size / 1024 ) / 1024 , "MB" )
}
go build filesize.go && ./filesize
ou go run filesize.go
Until the next article!
clanguage
cpp
java
lua
perl
python
php
csharp
javascript
nodejs
go
programming
langs
Marcos Oliveira
Software developer