ext/dl/sample/drives.rb


DEFINITIONS

This source file includes following functions.


   1  # -*- ruby -*-
   2  # drives.rb -- find existing drives and show the drive type.
   3  
   4  require 'dl'
   5  require 'dl/import'
   6  
   7  module Kernel32
   8    extend DL::Importable
   9  
  10    dlload "kernel32"
  11  
  12    extern "long GetLogicalDrives()"
  13    extern "int GetDriveType(char*)"
  14    extern "long GetDiskFreeSpace(char*, long ref, long ref, long ref, long ref)"
  15  end
  16  
  17  include Kernel32
  18  
  19  buff = Kernel32.getLogicalDrives()
  20  
  21  i = 0
  22  ds = []
  23  while( i < 26 )
  24    mask = (1 << i)
  25    if( buff & mask > 0 )
  26      ds.push((65+i).chr)
  27    end
  28    i += 1
  29  end
  30  
  31  =begin
  32  From the cygwin's /usr/include/w32api/winbase.h:
  33  #define DRIVE_UNKNOWN 0
  34  #define DRIVE_NO_ROOT_DIR 1
  35  #define DRIVE_REMOVABLE 2
  36  #define DRIVE_FIXED 3
  37  #define DRIVE_REMOTE 4
  38  #define DRIVE_CDROM 5
  39  #define DRIVE_RAMDISK 6
  40  =end
  41  
  42  types = [
  43    "unknown",
  44    "no root dir",
  45    "Removable",
  46    "Fixed", 
  47    "Remote",
  48    "CDROM",
  49    "RAM",
  50  ]
  51  print("Drive : Type (Free Space/Available Space)\n")
  52  ds.each{|d|
  53    t = Kernel32.getDriveType(d + ":\\")
  54    Kernel32.getDiskFreeSpace(d + ":\\", 0, 0, 0, 0)
  55    _,sec_per_clus,byte_per_sec,free_clus,total_clus = Kernel32._args_
  56    fbytes = sec_per_clus * byte_per_sec * free_clus
  57    tbytes = sec_per_clus * byte_per_sec * total_clus
  58    unit = "B"
  59    if( fbytes > 1024 && tbytes > 1024 )
  60      fbytes = fbytes / 1024
  61      tbytes = tbytes / 1024
  62      unit = "K"
  63    end
  64    if( fbytes > 1024 && tbytes > 1024 )
  65      fbytes = fbytes / 1024
  66      tbytes = tbytes / 1024
  67      unit = "M"
  68    end
  69    print("#{d} : #{types[t]} (#{fbytes} #{unit}/#{tbytes} #{unit})\n")
  70  }