ファイルサイズの取得
Posted feedbacks - Flatten
Nested Hiddenone-liner で
perl -e 'print -s _ if -f shift' ファイル名
Fan 1.0.38で。
1 2 3 4 5 6 7 8 9 10 | class Doukaku243
{
Void main(Str[] args) {
args.each |Str filepath| {
f := File.os(filepath)
if (f.exists)
echo("${f.name}: ${f.size}")
}
}
}
|
Squeak Smalltalk で。
1 2 3 4 | | path entry |
path := 'C:\path\to\a\file'.
entry := FileDirectory directoryEntryFor: path.
entry ifNotNil: [entry fileSize]
|
Rubyで。
1 2 | filepath = "/some/where/file"
puts "#{filepath}: #{FileTest.size(filepath)}" if FileTest.exist?(filepath)
|
1 2 3 4 | from os import path
filename = 'hoge.txt'
print path.getsize(filename) if path.isfile(filename) else -1
|
JScript で。
1 2 3 4 5 6 7 8 9 10 11 12 13 | function fileSize(filepath){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file;
if (fso.FileExists(filepath)){
file=fso.GetFile(filepath);
return file.Size;
} else {
return "ファイル「" + filepath + "」が存在しません。"
}
}
var filepath = "./ファイルサイズ.js";
WScript.Echo(fileSize(filepath));
|
1 | (dir filepath).length
|
ファイルが存在しない場合は「_」を返します。 fsize 'jconsole.exe' 40960 fsize 'pconsole.exe' _
1 | fsize =: 1!:4&< :: _:
|
1 2 3 4 5 6 | open Unix;;
print_string
(try
Printf.sprintf "%d\n" (stat Sys.argv.(1)).st_size
with _ -> "Not found\n")
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | using System;
using System.IO;
class Pair<S, T>
{
public S s { get; set; }
public T t { get; set; }
public Pair(S s, T t) { this.s = s; this.t = t; }
public Pair() { s = default(S); t = default(T); }
}
static class P
{
static void Main(string[] args)
{
string path = @"C:\Windows\System32\ANSI.SYS";
FileInfo info = new FileInfo(path);
if (info.Exists)
Console.WriteLine("Size : {0}", ToReadable(info.Length));
}
static Pair<decimal, string> Shorten(long fileSize)
{
if (fileSize < 100)
return new Pair<decimal, string>(fileSize, "B");
else if (fileSize < 1000 * 1000)
return new Pair<decimal, string>(fileSize / 1000.0m, "KB");
else if (fileSize < 1000 * 1000 * 1000)
return new Pair<decimal, string>(fileSize / (1000 * 1000.0m), "MB");
else if (fileSize < (long)1000 * 1000 * 1000 * 1000)
return new Pair<decimal, string>(fileSize / (1000 * 1000 * 1000.0m), "GB");
else
return new Pair<decimal, string>(fileSize / (1000 * 1000 * 1000 * 1000.0m), "TB");
}
static string ToReadable(long fileSize)
{
var tmp = Shorten(fileSize);
return string.Format("{0:F1}{1}", tmp.s, tmp.t);
}
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
int main (int argc, char *argv[]){
if( argc < 2 ){
return 1;
}
struct stat sb;
if( 0 != stat(argv[1], &sb) ){
perror(NULL);
return 1;
}
printf("File size: %d\n", sb.st_size);
return 0;
}
|
Perl 5.10 からはファイルテスト演算子を積み重ねる事ができるようになりました。 一行野郎版 perl -E 'print -s -f shift' ファイル名
see: スタックされたファイルテスト演算子
1 2 | use feature ":5.10";
print -s -f shift;
|
実行例 *Main> getFileSize "getFileSize.hs" Just 294 *Main> getFileSize "notExist.hs" Nothing
1 2 3 4 5 6 7 8 9 10 11 | {-# OPTIONS_GHC -cpp #-}
#if __GLASGOW_HASKELL__ > 608
import Control.OldException
#else
import Control.Exception
#endif
import System.IO
getFileSize path = handle (const $ return Nothing)
$ bracket (openFile path ReadMode) hClose
$ (Just `fmap`) . hFileSize
|
コマンドラインでgroovyを使った例を。
1 | groovy -e 'println new File(args[0]).size()' lastData.csv
|
引数にファイル名を渡すと、そのサイズを出力します。
1 2 3 4 5 6 7 8 | public class Sample243 {
public static void main(String[] args) {
File f = new File(args[0]);
if (f.exists()) {
System.out.println(f.length() + " byte(s)");
}
}
}
|
1 2 3 | FILE="C:\TEST"
もし、FILEが存在ならば
FILEのファイルサイズを表示
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream>
#include <fstream>
int getFileSize(const char* filename)
{
return std::ifstream(filename, std::ios::binary).seekg(0, std::ios::end).tellg();
}
int main(int argc, char* argv[])
{
for(int i = 1; i < argc; ++i)
{
int size = getFileSize(argv[i]);
if(size >= 0)
{
std::cout << argv[i] << " : " << size << " byte(s)" << std::endl;
}
else
{
std::cout << argv[i] << " not found" << std::endl;
}
}
return 0;
}
|
コードはDelphiですが、コンパイル&動作確認はDelphi互換モードのFreePascalで行っています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | program doukaku243;
uses
SysUtils;
function GetFileSize(const Filename: String): Integer;
var
rec: TSearchRec;
begin
if FindFirst(Filename, faAnyFile, rec) = 0 then
result := rec.Size
else
result := -1;
FindClose(rec);
end;
var
i, Size: Integer;
begin
for i := 1 to ParamCount do
begin
Write(ParamStr(i), ' ');
Size := GetFileSize(ParamStr(i));
if Size >= 0 then
Writeln(Size, ' byte(s)')
else
Writeln('not found');
end;
end.
|
stat(1)で。
1 2 3 4 5 | # GNU coreutils(Linux等)の場合
[ -f hoge.txt ] && stat -c %s hoge.txt
# FreeBSD系(Mac OS Xを含む)の場合
[ -f hoge.txt ] && stat -f %z hoge.txt
|
一度ストリームを開く必要がある?
1 2 3 4 5 6 | (let ((file "foo"))
(with-open-file (s file :direction :input
:element-type '(unsigned-byte 8)
:if-does-not-exist nil)
(when s
(princ (file-length s)))))
|
Windows NTでは無理ですが、これで。
e.g.
C:\>#243.bat A.txt B.txt
C:\A.txt 1024
C:\B.txt 2048
1 2 3 4 5 | :: #243.bat
@echo off
for %%i in (%*) do (
if exist "%%~fi" echo %%~fi %%~zi
)
|
“エラーが起きること”イコール“ファイルがないこと”ではないと思いますが・
その通りですね。修正しました。
1 2 3 4 5 6 | open Unix;;
print_endline
(try
string_of_int (stat Sys.argv.(1)).st_size
with Unix_error (ENOENT, _, _) -> "Not found")
|
1 | filesize <- function(f) if(file.exists(f)) file.info(f)$size
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | if(file_exists($filepath)){
$size = filesize($filepath);
$unim = array("Bytes","KB","MB","GB","TB","PB");
$count=0;
while($size >= 1024 ){
$count++;
$size = $size/1024;
}
$size = round($size,2);
echo $size.$unim[$count];
}else{
echo "not exists";
}
}
|
標準手続きだけで。
1 2 3 4 5 6 7 8 9 | (import (rnrs))
(let ((fn (cadr (command-line))))
(when (file-exists? fn)
(display
(bytevector-length
(call-with-port (open-file-input-port fn)
get-bytevector-all)))
(newline)))
|
1 2 3 4 | exist filepath
if strsize != -1 {
mes ""+strsize+" バイト"
}
|
vim scriptで。
1 2 3 4 5 | function! EchoFileSize(filename)
if getftype(a:filename) ==# "file"
echo getfsize(a:filename)
endif
endfunction
|
「表示してください」の解釈に悩みましたが、とりあえず。
1 2 3 | (let ((filename "hoge"))
(if (file-exists-p filename)
(message "File size: %d" (nth 7 (file-attributes filename))) ))
|
HSPの得意分野なので、若干凝ってインクリメンタル・サーチっぽくしてみた
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | // No.243 : ファイルサイズを取得
*main
sdim filepath, 260
filepath = dirinfo(0)
pos 10, 10 : input filepath, 256, 20
onkey gosub *OnKeyEvent
repeat
redraw 2
color 255, 255, 255 : boxf : color
dirlist filelist1, filepath +"*?", 1
dirlist filelist2, filepath +"\\*.*", 1
pos 10, 30 : mes filelist1 +"\n"+ filelist2
redraw 1
wait 5
loop
stop
*OnKeyEvent
if ( iparam == 13 ) {
exist filepath
if ( strsize < 0 ) {
dialog "["+ filepath +"]\nは存在しない", 1, "Error"
} else {
dialog "["+ filepath +"]\nサイズ:"+ strsize +" bytes"
}
}
return
|
わざわざ開かなくても probe-file では如何でしょう?
ごめんなさい、勘違いしてました。#8741は無視してください。
Limboではsys-statを使用してディレクトリ・ファイルの 情報を参照できます。 なお、演算子の優先順は&よりも==の方が高いらしく、 なぜかはまりました(Cと同じはずなんですが)。 サンプルコードは引数をパス名とみなし、 そのパスが指すオブジェクトが存在するファイルであればサイズを表示します。 意外とファイルサイズ取得方法が見つからず、 duのソースコードから探しました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | implement d243;
include "sys.m";
sys: Sys;
include "draw.m";
d243: module{
init: fn(ctx: ref Draw->Context, argv: list of string);
};
init(ctx: ref Draw->Context, argv: list of string)
{
sys = load Sys Sys->PATH;
argv = tl argv;
if(argv == nil){
return;
}
name := hd argv;
(rc, d) := sys->stat(name);
if((rc >= 0) && ((d.mode & Sys->DMDIR) == 0)){
sys->print ("%s: %d\n", name, int d.length);
}
}
|
scalaがまだの様なので。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import java.io.File
object FileSize {
def main(args:Array[String]):Unit = {
args.size match {
case 1 => {
var f = new File(args.first)
f.exists match {
case true => printf("%s bytes\n", f.length)
case _ => println("file not exist.")
}
}
case _ => println("usage: scala FileSize FILENAME")
}
}
}
|
1 2 | print (Int.toString (OS.FileSys.fileSize (hd (CommandLine.arguments ()))) ^ "\n"
handle _ => "Not found\n");
|
file_size.erlで保存し、以下のように実行します。:
$ erl -noshell -s file_size file_size file_size.erl -s init stop 189
存在しないファイル(例えばdummy.txtとする)を指定すると、何も表示されません。:
$ erl -noshell -s file_size file_size dummy.txt -s init stop
1 2 3 4 5 6 7 8 | -module(file_size).
-export([file_size/1]).
file_size(Name) ->
case filelib:is_file(Name) of
false -> ok;
true -> io:format("~B~n", [filelib:file_size(Name)])
end.
|
コマンドライン引数で与えたパスを順にチェックします
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import std.file: exists, isfile, getSize;
import std.stdio;
void main(string[] args) {
foreach(file; args[1..$]) {
if(file.exists) {
if(file.isfile) {
writefln("'%s' has the size of %s byte(s).", file, file.getSize);
} else {
writefln("'%s' is not a file.", file);
}
} else {
writefln("'%s' does not exist.", file);
}
}
}
|
複数ファイルに対応してみたり。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import java.io.File
object fileinfo {
def main(args : Array[String]) : Unit = {
try{
for{arg<-args
f = new File(arg)
if f.isFile && f.exists}{
println("size of "+arg+"="+f.length)
}
}catch{
case e:Exception => println(e)
case _ =>
}
}
}
|
Erlang初投稿です。よろしくお願いします。 とりあえず、システムコールを呼ぶ回数を1回にしました。 erlide(Eclipse)で確認しました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | -module(file_size).
-export([file_size/1]).
-include_lib("kernel/include/file.hrl").
file_size(Name) ->
try file:read_file_info(Name) of
{ok,Fileinfo} ->
case Fileinfo#file_info.type of
regular ->
io:format("~B~n",[Fileinfo#file_info.size]);
_ -> ok % except file
end;
_ -> ok % cannot get infomation
catch
_ -> ok % exception
end.
|
Boost.Filesystemを使ったものがまだ投稿されていないので書きました。existsが存在確認、file_sizeが大きさの取得です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <iostream>
#include <boost/filesystem.hpp>
int main()
{
namespace fs = boost::filesystem;
fs::path p;
std::cin >> p;
if (fs::exists(p))
{
std::cout << "size: " << fs::file_size(p) << " bytes." << std::endl;
}
else
{
std::cout << "Not found." << std::endl;
}
}
|
VBScriptで書きました。 自分が思っている以上にマイナーな言語なのですね。
1 2 3 4 5 6 7 8 9 10 11 | If WScript.Arguments.Count <> 1 Then
WScript.Quit(1)
End If
inFileName = WScript.Arguments(0)
Set fs = CreateObject("Scripting.FileSystemObject")
If fs.FileExists(inFileName) Then
Set objFile = fs.GetFile(inFileName)
WScript.Echo "FileSize = " & objFile.Size
End If
|





ところてん
#8633()
Rating2/2=1.00
[ reply ]