添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
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:

  • How to Get the Current Directory in 10 Different Programming Languages
  • 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

    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

    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

    file = io.open("file.iso", "r")
    size = math.floor((file:seek("end") / 1024) / 1024)
    print(size .. " MB")

    lua filesize.lua

    path = "file.iso" size = os.path.getsize(path) print( str( int( (size / 1024) / 1024) ) + " MB")

    python filesize.py

    $path = "file.iso" ; $x = filesize ( $path ) / 1024 / 1024 ; echo intval ( $x ) . " MB \n " ;

    php filesize.php

    string path = "file.iso";
    long size = new System.IO.FileInfo(path).Length;
    Console.WriteLine( (size/1024) / 1024 + " MB" );

    dotnet run

    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