How to Check File Size in 10 Programming Languages
C, C++, Java, Lua, Perl, Python, PHP, C#, JavaScript/Nodejs and Go.
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
02. C++
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
03. Java
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
04. Lua
filesize.lua
file = io.open("file.iso", "r")
size = math.floor((file:seek("end") / 1024) / 1024)
print(size .. " MB")
lua filesize.lua
05. Perl
filesize.pl
$path = "file.iso";
my $x = -s $path;
$x = ($x / 1024) / 1024;
$x = int($x);
print("$x MiB\n");
perl filesize.pl
06. Python
filesize.py
import os
path = "file.iso"
size = os.path.getsize(path)
print( str( int( (size / 1024) / 1024) ) + " MB")
python filesize.py
07. PHP
filesize.php
<?php
$path = "file.iso";
$x = filesize($path) / 1024 / 1024;
echo intval($x) . " MB\n";
php filesize.php
08. C#
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
09. JavaScript/Node.js
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
10. Golang/Go
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
ougo run filesize.go
Until the next article!
clanguage cpp java lua perl python php csharp javascript nodejs go programming langs
Comments