#!/bin/sh
set -eu

tabs -8
if [ ${GNU:-} ]
then
    find -- "${1:-.}" -type f -exec du -b -- {} +
else
    # Use a subshell to remove the last "total" line per each ARG_MAX
    find -- "${1:-.}" -type f -exec sh -c 'wc -c -- "[email protected]" | sed \$d' argv0 {} +
fi | awk -vOFS='\t' '
    BEGIN {split("KB MB GB TB PB", u); u[0] = "B"}
    {
        ++hist[$1 ? length($1) - 1 : -1]
        total += $1
    }
    END {
        max = -2
        for (i in hist)
            max = (i > max ? i : max)

        print "From", "To", "Count\n"
        for (i = -1; i <= max; ++i)
        {
            if (i in hist)
            {
                if (i == -1)
                    print "0B", "0B", hist[i]
                else
                    print 10 ** (i       % 3) u[int(i       / 3)],
                          10 ** ((i + 1) % 3) u[int((i + 1) / 3)],
                          hist[i]
            }
        }
        l = length(total) - 1
        printf "\nTotal: %.1f %s in %d files\n",
            total / (10 ** l), u[int(l / 3)], NR
    }'


import "io" for Directory, File, Stat
import "os" for Process
import "/math" for Math
import "/fmt" for Fmt

var sizes = List.filled(12, 0)
var totalSize = 0
var numFiles = 0
var numDirs = 0

var fileSizeDist // recursive function
fileSizeDist = Fn.new { |path|
    var files = Directory.list(path)
    for (file in files) {
        var path2 = "%(path)/%(file)"
        var stat = Stat.path(path2)
        if (stat.isFile) {
            numFiles = numFiles + 1
            var size = stat.size
            if (size == 0) {
                sizes[0] = sizes[0] + 1
            } else {
                totalSize = totalSize + size
                var logSize = Math.log10(size)
                var index = logSize.floor + 1
                sizes[index] = sizes[index] + 1
            }
        } else if (stat.isDirectory) {
            numDirs = numDirs + 1
            fileSizeDist.call(path2)
        }
    }
}

var args = Process.arguments
var path = (args.count == 0) ? "./" : args[0]
if (!Directory.exists(path)) Fiber.abort("Path does not exist or is not a directory.")
fileSizeDist.call(path)

System.print("File size distribution for '%(path)' :-\n")
for (i in 0...sizes.count) {
    System.write((i == 0) ? "  " : "+ ")
    Fmt.print("Files less than 10 ^ $-2d bytes : $,5d", i, sizes[i])
}
System.print("                                  -----")
Fmt.print("= Number of files               : $,5d", numFiles)
Fmt.print("  Total size in bytes           : $,d", totalSize)
Fmt.print("  Number of sub-directories     : $,5d", numDirs)


defmodule RC do
  def common_directory_path(dirs, separator \\ "/") do
    dir1 = Enum.min(dirs) |> String.split(separator)
    dir2 = Enum.max(dirs) |> String.split(separator)
    Enum.zip(dir1,dir2) |> Enum.take_while(fn {a,b} -> a==b end)
                        |> Enum.map_join(separator, fn {a,a} -> a end)
  end
end

dirs = ~w( /home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members )
IO.inspect RC.common_directory_path(dirs)


-module( find_common_directory ).

-export( [path/2, task/0] ).

path( [Path | T], _Separator ) -> filename:join( lists:foldl(fun keep_common/2, filename:split(Path), [filename:split(X) || X <- T]) ).

task() -> path( ["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"], "/" ).

keep_common( Components, Acc ) -> [X || X <- Components, Y <- Acc, X =:= Y].


open System

let (|SeqNode|SeqEmpty|) s =
    if Seq.isEmpty s then SeqEmpty
    else SeqNode ((Seq.head s), Seq.skip 1 s)

[<EntryPoint>]
let main args =
    let splitBySeparator (str : string) = Seq.ofArray (str.Split('/'))

    let rec common2 acc = function
        | SeqEmpty -> Seq.ofList (List.rev acc)
        | SeqNode((p1, p2), rest) ->
            if p1 = p2 then common2 (p1::acc) rest
            else Seq.ofList (List.rev acc)

    let commonPrefix paths =
        match Array.length(paths) with
        | 0 -> [||]
        | 1 -> Seq.toArray (splitBySeparator paths.[0])
        | _ ->
            let argseq = Seq.ofArray paths
            Seq.fold (
                fun (acc : seq<string>) items ->
                    common2 [] (List.ofSeq (Seq.zip acc (splitBySeparator items)))
            ) (splitBySeparator (Seq.head argseq)) (Seq.skip 1 argseq)
            |> Seq.toArray

    printfn "The common preffix is: %A" (String.Join("/", (commonPrefix args)))
    0


pipe:=Thread.Pipe();
    // hoover all files in tree, don't return directories
fcn(pipe,dir){ File.globular(dir,"*",True,8,pipe); }
.launch(pipe,vm.arglist[0]);  // thread

dist,N,SZ,maxd:=List.createLong(50,0),0,0,0;
foreach fnm in (pipe){
   sz,szd:=File.len(fnm), sz.numDigits;
   dist[szd]+=1;
   N+=1; SZ+=sz; maxd=maxd.max(szd);
}
println("Found %d files, %,d bytes, %,d mean.".fmt(N,SZ,SZ/N));
scale:=50.0/(0.0).max(dist);
szchrs,idx,comma:=",nnn"*20, -1, Walker.cycle(0,0,1).next;
println("%15s   %s (* = %.2f)".fmt("File size","Number of files",1.0/scale));
foreach sz,cnt in ([0..].zip(dist[0,maxd])){
   println("%15s : %s".fmt(szchrs[idx,*], "*"*(scale*cnt).round().toInt()));
   idx-=1 + comma();
}


: take-shorter ( seq1 seq2 -- shorter )
    [ shorter? ] 2keep ? ;

: common-head ( seq1 seq2 -- head )
    2dup mismatch [ nip head ] [ take-shorter ] if* ;

: common-prefix-1 ( file1 file2 separator -- prefix )
    [ common-head ] dip '[ _ = not ] trim-tail ;

: common-prefix ( seq separator -- prefix )
    [ ] swap '[ _ common-prefix-1 ] map-reduce ;


' compile: fbc.exe -s console cdp.bas

Function CommonDirectoryPath Cdecl(count As Integer, ...) As String
Dim As String Path(), s
Dim As Integer i, j, k = 1
Dim arg As Any Ptr
Const PATH_SEPARATOR As String = "/"

  arg = va_first()
  ReDim Preserve Path(1 To count)
  For i = 1 To count
    Path(i) = *Va_Arg(arg, ZString Ptr)
	Print Path(i)
    arg = va_next(arg, ZString Ptr)
  Next i

  Do
    For i = 1 To count
      If i > 1 Then
        If InStr(k, Path(i), PATH_SEPARATOR) <> j Then
          Exit Do
        ElseIf Left(Path(i), j) <> Left(Path(1), j) Then
          Exit Do
        End If
      Else
        j = InStr(k, Path(i), PATH_SEPARATOR)
        If j = 0 Then
          Exit Do
        End If
      End If
    Next i
    s = Left(Path(1), j + CLng(k <> 1))
    k = j + 1
  Loop
  Return s

End Function

' testing the above function

Print CommonDirectoryPath( 3, _
  "/home/user1/tmp/coverage/test", _
  "/home/user1/tmp/covert/operator", _
  "/home/user1/tmp/coven/members") & " <- common"
Print

Print CommonDirectoryPath( 4, _
  "/home/user1/tmp/coverage/test", _
  "/home/user1/tmp/covert/operator", _
  "/home/user1/tmp/coven/members", _
  "/home/user1/abc/coven/members") & " <- common"
Print

Print CommonDirectoryPath( 3, _
  "/home/user1/tmp/coverage/test", _
  "/hope/user1/tmp/covert/operator", _
  "/home/user1/tmp/coven/members") & " <- common"
Print

' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


Public Sub Main()
Dim sFolder As String[] = ["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"]
Dim sSame As String
Dim siCount As Short = 1

Do
  If Mid(sFolder[0], siCount, 1) = Mid(sFolder[1], siCount, 1) And Mid(sFolder[0], siCount, 1) = Mid(sFolder[2], siCount, 1) Then
    sSame &= Mid(sFolder[0], siCount, 1)
  Else
    Break
  End If
  Inc siCount
Loop

Print Mid(sSame, 1, RInStr(sSame, "/") - 1)

End


package main

import (
	"fmt"
	"os"
	"path"
)

func CommonPrefix(sep byte, paths ...string) string {
	// Handle special cases.
	switch len(paths) {
	case 0:
		return ""
	case 1:
		return path.Clean(paths[0])
	}

	// Note, we treat string as []byte, not []rune as is often
	// done in Go. (And sep as byte, not rune). This is because
	// most/all supported OS' treat paths as string of non-zero
	// bytes. A filename may be displayed as a sequence of Unicode
	// runes (typically encoded as UTF-8) but paths are
	// not required to be valid UTF-8 or in any normalized form
	// (e.g. "é" (U+00C9) and "é" (U+0065,U+0301) are different
	// file names.
	c := []byte(path.Clean(paths[0]))

	// We add a trailing sep to handle the case where the
	// common prefix directory is included in the path list
	// (e.g. /home/user1, /home/user1/foo, /home/user1/bar).
	// path.Clean will have cleaned off trailing / separators with
	// the exception of the root directory, "/" (in which case we
	// make it "//", but this will get fixed up to "/" bellow).
	c = append(c, sep)

	// Ignore the first path since it's already in c
	for _, v := range paths[1:] {
		// Clean up each path before testing it
		v = path.Clean(v) + string(sep)

		// Find the first non-common byte and truncate c
		if len(v) < len(c) {
			c = c[:len(v)]
		}
		for i := 0; i < len(c); i++ {
			if v[i] != c[i] {
				c = c[:i]
				break
			}
		}
	}

	// Remove trailing non-separator characters and the final separator
	for i := len(c) - 1; i >= 0; i-- {
		if c[i] == sep {
			c = c[:i]
			break
		}
	}

	return string(c)
}

func main() {
	c := CommonPrefix(os.PathSeparator,
		//"/home/user1/tmp",
		"/home/user1/tmp/coverage/test",
		"/home/user1/tmp/covert/operator",
		"/home/user1/tmp/coven/members",
		"/home//user1/tmp/coventry",
		"/home/user1/././tmp/covertly/foo",
		"/home/bob/../user1/tmp/coved/bar",
	)
	if c == "" {
		fmt.Println("No common path")
	} else {
		fmt.Println("Common path:", c)
	}
}


def commonPath = { delim, Object[] paths ->
    def pathParts = paths.collect { it.split(delim) }
    pathParts.transpose().inject([match:true, commonParts:[]]) { aggregator, part ->
        aggregator.match = aggregator.match && part.every { it == part [0] }
        if (aggregator.match) { aggregator.commonParts << part[0] }
        aggregator
    }.commonParts.join(delim)
}


10 REM All GOTO statements can be replaced with EXIT FOR in newer BASICs.

110 X$ = "/home/user1/tmp/coverage/test"
120 Y$ = "/home/user1/tmp/covert/operator"
130 Z$ = "/home/user1/tmp/coven/members"

150 A = LEN(X$)
160 IF A > LEN(Y$) THEN A = LEN(Y$)
170 IF A > LEN(Z$) THEN A = LEN(Z$)
180 FOR L0 = 1 TO A
190     IF MID$(X$, L0, 1) <> MID$(Y$, L0, 1) THEN GOTO 210
200 NEXT
210 A = L0 - 1

230 FOR L0 = 1 TO A
240     IF MID$(X$, L0, 1) <> MID$(Z$, L0, 1) THEN GOTO 260
250 NEXT
260 A = L0 - 1

280 IF MID$(X$, L0, 1) <> "/" THEN
290     FOR L0 = A TO 1 STEP -1
300        IF "/" = MID$(X$, L0, 1) THEN GOTO 340
310     NEXT
320 END IF

340 REM Task description says no trailing slash, so...
350 A = L0 - 1
360 P$ = LEFT$(X$, A)
370 PRINT "Common path is '"; P$; "'"


import Data.List

-- Return the common prefix of two lists.
commonPrefix2 (x:xs) (y:ys) | x == y = x : commonPrefix2 xs ys
commonPrefix2 _ _ = []

-- Return the common prefix of zero or more lists.
commonPrefix (xs:xss) = foldr commonPrefix2 xs xss
commonPrefix _ = []

-- Split a string into path components.
splitPath = groupBy (\_ c -> c /= '/')

-- Return the common prefix of zero or more paths.
-- Note that '/' by itself is not considered a path component,
-- so "/" and "/foo" are treated as having nothing in common.
commonDirPath = concat . commonPrefix . map splitPath

main = putStrLn $ commonDirPath [
        "/home/user1/tmp/coverage/test",
        "/home/user1/tmp/covert/operator",
        "/home/user1/tmp/coven/members"
       ]


CHARACTER a='/home/user1/tmp/coverage/test', b='/home/user1/tmp/covert/operator', c='/home/user1/tmp/coven/members'

minLength = MIN( LEN(a), LEN(b), LEN(c) )
lastSlash = 0

DO i = 1, minLength
  IF( (a(i) == b(i)) * (b(i) == c(i)) ) THEN
    IF(a(i) == "/") lastSlash = i
  ELSEIF( lastSlash ) THEN
    WRITE(Messagebox) "Common Directory = ", a(1:lastSlash-1)
  ELSE
    WRITE(Messagebox, Name) "No common directory for", a, b, c
  ENDIF
ENDDO


procedure main()
write(lcdsubstr(["/home/user1/tmp/coverage/test","/home/user1/tmp/covert/operator","/home/user1/tmp/coven/members"]))
end

procedure lcdsubstr(sL,d)   #: return the longest common sub-string of strings in the list sL delimited by d
local ss

/d := "/"
reverse(sL[1]) ? {
   if tab(find(d)+*d) || allmatch(ss := reverse(tab(0)),sL) then
      return ss
   }
end

procedure allmatch(s,L)   #: retrun s if it matches all strings in L
local x
every x := !L do
   if not match(s,x) then fail
return s
end


parseDirs       =: = <;.2 ]
getCommonPrefix =: {. ;@{.~ 0 i.~ *./@(="1 {.)

getCommonDirPath=: [: getCommonPrefix parseDirs&>


public class CommonPath {
	public static String commonPath(String... paths){
		String commonPath = "";
		String[][] folders = new String[paths.length][];
		for(int i = 0; i < paths.length; i++){
			folders[i] = paths[i].split("/"); //split on file separator
		}
		for(int j = 0; j < folders[0].length; j++){
			String thisFolder = folders[0][j]; //grab the next folder name in the first path
			boolean allMatched = true; //assume all have matched in case there are no more paths
			for(int i = 1; i < folders.length && allMatched; i++){ //look at the other paths
				if(folders[i].length < j){ //if there is no folder here
					allMatched = false; //no match
					break; //stop looking because we've gone as far as we can
				}
				//otherwise
				allMatched &= folders[i][j].equals(thisFolder); //check if it matched
			}
			if(allMatched){ //if they all matched this folder name
				commonPath += thisFolder + "/"; //add it to the answer
			}else{//otherwise
				break;//stop looking
			}
		}
		return commonPath;
	}

	public static void main(String[] args){
		String[] paths = { "/home/user1/tmp/coverage/test",
				 "/home/user1/tmp/covert/operator",
				 "/home/user1/tmp/coven/members"};
		System.out.println(commonPath(paths));

		String[] paths2 = { "/hame/user1/tmp/coverage/test",
				 "/home/user1/tmp/covert/operator",
				 "/home/user1/tmp/coven/members"};
		System.out.println(commonPath(paths2));
	}
}


/**
 * Given an array of strings, return an array of arrays, containing the
 * strings split at the given separator
 * @param {!Array<!string>} a
 * @param {string} sep
 * @returns {!Array<!Array<string>>}
 */
const splitStrings = (a, sep = '/') => a.map(i => i.split(sep));

/**
 * Given an index number, return a function that takes an array and returns the
 * element at the given index
 * @param {number} i
 * @return {function(!Array<*>): *}
 */
const elAt = i => a => a[i];

/**
 * Transpose an array of arrays:
 * Example:
 * [['a', 'b', 'c'], ['A', 'B', 'C'], [1, 2, 3]] ->
 * [['a', 'A', 1], ['b', 'B', 2], ['c', 'C', 3]]
 * @param {!Array<!Array<*>>} a
 * @return {!Array<!Array<*>>}
 */
const rotate = a => a[0].map((e, i) => a.map(elAt(i)));

/**
 * Checks of all the elements in the array are the same.
 * @param {!Array<*>} arr
 * @return {boolean}
 */
const allElementsEqual = arr => arr.every(e => e === arr[0]);

const commonPath = (input, sep = '/') => rotate(splitStrings(input, sep))
    .filter(allElementsEqual).map(elAt(0)).join(sep);

const cdpInput = [
  '/home/user1/tmp/coverage/test',
  '/home/user1/tmp/covert/operator',
  '/home/user1/tmp/coven/members',
];

console.log(`Common path is: ${commonPath(cdpInput)}`);


# maximal_initial_subarray takes as input an array of arrays:
def maximal_initial_subarray:
  (map( .[0] ) | unique) as $u
  | if $u == [ null ] then []
    elif ($u|length) == 1
    then  $u  + ( map( .[1:] ) | maximal_initial_subarray)
    else []
    end ;

# Solution: read in the strings, convert to an array of arrays, and proceed:
def common_path(slash):
  [.[] | split(slash)] | maximal_initial_subarray | join(slash) ;

common_path("/")


function commonpath(ds::Vector{<:AbstractString}, dlm::Char='/')
    0 < length(ds) || return ""
    1 < length(ds) || return String(ds[1])
    p = split(ds[1], dlm)
    mincnt = length(p)
    for d in ds[2:end]
        q = split(d, dlm)
        mincnt = min(mincnt, length(q))
        hits = findfirst(p[1:mincnt] .!= q[1:mincnt])
        if hits != 0 mincnt = hits - 1 end
        if mincnt == 0 return "" end
    end
    1 < mincnt || p[1] != "" || return convert(T, string(dlm))
    return join(p[1:mincnt], dlm)
end

test = ["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"]

println("Comparing:\n - ", join(test, "\n - "))
println("for their common directory path yields:\n", commonpath(test))


// version 1.1.51

fun findCommonDirPath(paths: List<String>, separator: Char): String {
    if (paths.isEmpty()) return ""
    if (paths.size == 1) return paths[0]
    val splits = paths[0].split(separator)
    val n = splits.size
    val paths2 = paths.drop(1)
    var k = 0
    var common = ""
    while (true) {
        val prevCommon = common
        common += if (k == 0) splits[0] else separator + splits[k]
        if (!paths2.all { it.startsWith(common + separator) || it == common } ) return prevCommon
        if (++k == n) return common
    }
}

fun main(args: Array<String>) {
    val paths = listOf(
        "/home/user1/tmp/coverage/test",
        "/home/user1/tmp/covert/operator",
        "/home/user1/tmp/coven/members"
    )
    val pathsToPrint = paths.map { "   '$it'" }.joinToString("\n")
    println("The common directory path of:\n\n$pathsToPrint\n")
    println("is '${findCommonDirPath(paths, '/')}'")
}


#!/usr/bin/lasso9

local(
	path1 = '/home/user1/tmp/coverage/test' -> split('/'),
	path2 = '/home/user1/tmp/covert/operator' -> split('/'),
	path3 = '/home/user1/tmp/coven/members' -> split('/')
)

define commonpath(...) => {
	local(shared = #rest -> get(1))
	loop(#rest -> size - 1) => {
		#shared = #shared -> intersection(#rest -> get(loop_count + 1))
	}
	return #shared -> join('/')
}

stdoutnl(commonpath(#path1, #path2, #path3))


path$(1) = "/home/user1/tmp/coverage/test"
path$(2) = "/home/user1/tmp/covert/operator"
path$(3) = "/home/user1/tmp/coven/members"

print samepath$(3,"/")
end

function samepath$(paths,sep$)
    d = 1 'directory depth
    n = 2 'path$(number)
    while 1
        if word$(path$(1),d,sep$) <> word$(path$(n),d,sep$) or word$(path$(1),d,sep$) = "" then exit while
        n = n + 1
        if n > paths then
            if right$(samepath$,1) <> sep$ and d<>1 then
                samepath$ = samepath$ + sep$ + word$(path$(1),d,sep$)
            else
                samepath$ = samepath$ + word$(path$(1),d,sep$)
            end if
            n = 2
            d = d + 1
        end if
    wend
end function


on getCommonPath (pathes, sep)
  _player.itemDelimiter = sep

  -- find length of shortest path (in terms of items)
  commonCnt = the maxInteger
  repeat with p in pathes
    if p.item.count<commonCnt then commonCnt=p.item.count
  end repeat

  pathCnt = pathes.count
  repeat with i = 1 to commonCnt
    repeat with j = 2 to pathCnt
      if pathes[j].item[i]<>pathes[j-1].item[i] then
        return pathes[1].item[1..i-1]
      end if
    end repeat
  end repeat
  return pathes[1].item[1..commonCnt]
end


Include "MapBasic.def"

DECLARE SUB Main
DECLARE FUNCTION commonPath(paths() AS STRING, BYVAL pathSep AS STRING) AS STRING

FUNCTION commonPath(paths() AS STRING, BYVAL pathSep AS STRING) AS STRING
    DIM tmpint1 AS INTEGER, tmpint2 AS INTEGER, tmpstr1 AS STRING, tmpstr2 AS STRING
    DIM L0 AS INTEGER, L1 AS INTEGER, lowerbound AS INTEGER, upperbound AS INTEGER

    lowerbound = 1
    upperbound = UBOUND(paths)

    IF (lowerbound) = upperbound THEN       'Some quick error checking...
        commonPath = paths(lowerbound)
    ELSEIF lowerbound > upperbound THEN     'How in the...?
        commonPath = ""
    ELSE
        tmpstr1 = paths(lowerbound)

        FOR L0 = (lowerbound) TO upperbound 'Find common strings.
            tmpstr2 = paths(L0)
            tmpint1 = LEN(tmpstr1)
            tmpint2 = LEN(tmpstr2)
            IF tmpint1 > tmpint2
            THEN tmpint1 = tmpint2

            FOR L1 = 1 TO tmpint1
                IF MID$(tmpstr1, L1, 1) <> MID$(tmpstr2, L1, 1) THEN
                    tmpint1 = L1 - 1
                    EXIT FOR
                END IF
            NEXT
                      END IF
           tmpstr1 = LEFT$(tmpstr1, tmpint1)
        NEXT

        IF RIGHT$(tmpstr1, 1) <> pathSep THEN
            FOR L1 = tmpint1 TO 2 STEP -1
                IF (pathSep) = MID$(tmpstr1, L1, 1) THEN
                    tmpstr1 = LEFT$(tmpstr1, L1 - 1)
                    EXIT FOR
                END IF
            NEXT
            IF LEN(tmpstr1) = tmpint1
            THEN tmpstr1 = ""
       		 ELSEIF tmpint1 > 1
       		 THEN
            tmpstr1 = LEFT$(tmpstr1, tmpint1 - 1)
        	END IF
 		 END IF
        commonPath = tmpstr1
    END IF
END FUNCTION

SUB Main()
	DIM x(3) AS  STRING
	Define Sep "/"

	x(1) = "/home/user1/tmp/"
	x(2) = "/home/user1/tmp/covert/operator"
	x(3) = "/home/user1/tmp/coven/members"

PRINT "Common path is " + commonPath(x(), Sep)

END SUB


dirpath:=proc(a,b,c)
	local dirtemp,dirnew,x;
	use StringTools in
		dirtemp:=LongestCommonSubString(c, LongestCommonSubString(a,b));
		x:=FirstFromRight("/",dirtemp);
		dirnew:=dirtemp[1..x];
	return dirnew;
	end use;
end proc;


FindCommonDirectory[x_] := If[StringTake[#, -1] != "/", StringTake[#, Max[StringPosition[#, "/"]]], #] &
 [Fold[LongestCommonSubsequence, First[x] , Rest[x]]]

FindCommonDirectory[{"/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}]
->"/home/user1/tmp/"


function lcp = longest_common_dirpath(varargin)
ix    = find(varargin{1}=='/');
ca    = char(varargin);
flag  = all(ca==ca(1,:),1);
for k = length(ix):-1:1,
	if all(flag(1:ix(k))); break; end
end
lcp = ca(1,1:ix(k));
end

longest_common_dirpath('/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members')


scommon(a, b) := block([n: min(slength(a), slength(b))],
   substring(a, 1, catch(for i thru n do (
   if not cequal(charat(a, i), charat(b, i)) then throw(i)), n + 1)))$

commonpath(u, [l]) := block([s: lreduce(scommon, u), c, n],
   n: sposition(if length(l) = 0 then "/" else l[1], sreverse(s)),
   if integerp(n) then substring(s, 1, slength(s) - n) else ""
)$

commonpath(["c:/files/banister.jpg", "c:/files/bank.xls", "c:/files/banana-recipes.txt"]);
"c:/files"


FCD
 NEW D,SEP,EQ,LONG,DONE,I,J,K,RETURN
 SET D(1)="/home/user1/tmp/coverage/test"
 SET D(2)="/home/user1/tmp/covert/operator"
 SET D(3)="/home/user1/tmp/coven/members"
 SET SEP="/"
 SET LONG=D(1)
 SET DONE=0
 FOR I=1:1:$LENGTH(LONG,SEP) QUIT:DONE  SET EQ(I)=1 FOR J=2:1:3 SET EQ(I)=($PIECE(D(J),SEP,I)=$PIECE(LONG,SEP,I))&EQ(I) SET DONE='EQ(I) QUIT:'EQ(I)
 SET RETURN=""
 FOR K=1:1:I-1 Q:'EQ(K)  SET:EQ(K) $PIECE(RETURN,SEP,K)=$PIECE(LONG,SEP,K)
 WRITE !,"For the paths:" FOR I=1:1:3 WRITE !,D(I)
 WRITE !,"The longest common directory is: ",RETURN
 KILL D,SEP,EQ,LONG,DONE,I,J,K,RETURN
 QUIT


import strutils

proc commonprefix(paths: openarray[string], sep = "/"): string =
  if paths.len == 0: return ""
  block outer:
    for i in 0 ..< paths[0].len:
      result = paths[0][0 .. i]
      for path in paths:
        if not path.startsWith(result):
          break outer
  result = result[0 .. result.rfind(sep)]

echo commonprefix(@["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"])


let rec aux acc paths =
  if List.mem [] paths
  then (List.rev acc) else
  let heads = List.map List.hd paths in
  let item = List.hd heads in
  let all_the_same =
    List.for_all ((=) item) (List.tl heads)
  in
  if all_the_same
  then aux (item::acc) (List.map List.tl paths)
  else (List.rev acc)

let common_prefix sep = function
  | [] -> invalid_arg "common_prefix"
  | dirs ->
      let paths = List.map (Str.split (Str.regexp_string sep)) dirs in
      let res = aux [] paths in
      (sep ^ (String.concat sep res))

let () =
  let dirs = [
    "/home/user1/tmp/coverage/test";
    "/home/user1/tmp/covert/operator";
    "/home/user1/tmp/coven/members";
  ] in
  print_endline (common_prefix "/" dirs);
;;


FUNCTION findCommonDir RETURNS CHAR(
   i_cdirs        AS CHAR,
   i_cseparator   AS CHAR
):

   DEF VAR idir      AS INT.
   DEF VAR idepth    AS INT.
   DEF VAR cdir      AS CHAR EXTENT.
   DEF VAR lsame     AS LOGICAL INITIAL TRUE.
   DEF VAR cresult   AS CHAR.

   EXTENT( cdir ) = NUM-ENTRIES( i_cdirs, '~n' ).

   DO idir = 1 TO NUM-ENTRIES( i_cdirs, '~n' ):
      cdir[ idir ] = ENTRY( idir, i_cdirs, '~n' ).
   END.

   DO idepth = 2 TO NUM-ENTRIES( cdir [ 1 ], i_cseparator ) WHILE lsame:
      DO idir = 1 TO EXTENT( cdir ) - 1 WHILE lsame:
         lsame =  (
                     ENTRY( idepth, cdir [ idir ], i_cseparator ) =
                     ENTRY( idepth, cdir [ idir + 1 ], i_cseparator )
                  ).
      END.
      IF lsame THEN
         cresult = cresult + i_cseparator + ENTRY( idepth, cdir [ 1 ], i_cseparator ).
   END.

   RETURN cresult.

END FUNCTION.


declare
  fun {CommonPrefix Sep Paths}
     fun {GetParts P} {String.tokens P Sep} end
     Parts = {ZipN {Map Paths GetParts}}
     EqualParts = {List.takeWhile Parts fun {$ X|Xr} {All Xr {Equals X}} end}
  in
     {Join Sep {Map EqualParts Head}}
  end

  fun {ZipN Xs}
     if {Some Xs {Equals nil}} then nil
     else
        {Map Xs Head} | {ZipN {Map Xs Tail}}
     end
  end

  fun {Join Sep Xs}
     {FoldR Xs fun {$ X Z} {Append X Sep|Z} end nil}
  end

  fun {Equals C}
     fun {$ X} X == C end
  end

  fun {Head X|_} X end

  fun {Tail _|Xr} Xr end
in
  {System.showInfo {CommonPrefix &/
                    ["/home/user1/tmp/coverage/test"
                     "/home/user1/tmp/covert/operator"
                     "/home/user1/tmp/coven/members"]}}


cdp(v)={
  my(s="");
  v=apply(t->Vec(t),v);
  for(i=1,vecmin(apply(length,v)),
    for(j=2,#v,
      if(v[j][i]!=v[1][i],return(s)));
      if(i>1&v[1][i]=="/",s=concat(vecextract(v[1],1<<(i-1)-1))
    )
  );
  if(vecmax(apply(length,v))==vecmin(apply(length,v)),concat(v[1]),s)
};
cdp(["/home/user1/tmp/coverage/test","/home/user1/tmp/covert/operator","/home/user1/tmp/coven/members"])


with javascript_semantics
function common_directory_path(sequence paths, integer sep='/')
    sequence res = {}
    if length(paths) then
        res = split(paths[1],sep)[1..-2]
        for i=2 to length(paths) do
            sequence pi = split(paths[i],sep)[1..-2]
            for j=1 to length(res) do
                if j>length(pi) or res[j]!=pi[j] then
                    res = res[1..j-1]
                    exit
                end if
            end for
            if length(res)=0 then exit end if
        end for
    end if
    return join(res,sep)
end function

constant test = {"/home/user1/tmp/coverage/test",
                 "/home/user1/tmp/covert/operator",
                 "/home/user1/tmp/coven/members"}
?common_directory_path(test)


<?php

/*
 This works with dirs and files in any number of combinations.
*/

function _commonPath($dirList)
{
	$arr = array();
	foreach($dirList as $i => $path)
	{
		$dirList[$i]	= explode('/', $path);
		unset($dirList[$i][0]);

		$arr[$i] = count($dirList[$i]);
	}

	$min = min($arr);

	for($i = 0; $i < count($dirList); $i++)
	{
		while(count($dirList[$i]) > $min)
		{
			array_pop($dirList[$i]);
		}

		$dirList[$i] = '/' . implode('/' , $dirList[$i]);
	}

	$dirList = array_unique($dirList);
	while(count($dirList) !== 1)
	{
		$dirList = array_map('dirname', $dirList);
		$dirList = array_unique($dirList);
	}
	reset($dirList);

	return current($dirList);
}

 /* TEST */

$dirs = array(
 '/home/user1/tmp/coverage/test',
 '/home/user1/tmp/covert/operator',
 '/home/user1/tmp/coven/members',
);

if('/home/user1/tmp' !== common_path($dirs))
{
  echo 'test fail';
} else {
  echo 'test success';
}

?>


find_common_directory_path(Dirs) = Path =>
  maxof( (common_prefix(Dirs,  Path,Len), append(_,"/",Path)), Len).

%
% Find a common prefix of all lists/strings in Ls.
% Using append/3.
%
common_prefix(Ls, Prefix,Len) =>
  foreach(L in Ls)
    append(Prefix,_,L)
  end,
  Len = Prefix.length.


(de commonPath (Lst Chr)
   (glue Chr
      (make
         (apply find
            (mapcar '((L) (split (chop L) Chr)) Lst)
            '(@ (or (pass <>) (nil (link (next))))) ) ) ) )


array paths = ({ "/home/user1/tmp/coverage/test",
                 "/home/user1/tmp/covert/operator",
                 "/home/user1/tmp/coven/members" });

// append a / to each entry, so that a path like "/home/user1/tmp" will be recognized as a prefix
// without it the prefix would end up being "/home/user1/"
paths = paths[*]+"/";

string cp = String.common_prefix(paths);
cp = cp[..sizeof(cp)-search(reverse(cp), "/")-2];
Result: "/home/user1/tmp"


#COMPILE EXE
#DIM ALL
#COMPILER PBCC 6
$PATH_SEPARATOR = "/"

FUNCTION CommonDirectoryPath(Paths() AS STRING) AS STRING
LOCAL s AS STRING
LOCAL i, j, k AS LONG
  k = 1
  DO
    FOR i = 0 TO UBOUND(Paths)
      IF i THEN
        IF INSTR(k, Paths(i), $PATH_SEPARATOR) <> j THEN
          EXIT DO
        ELSEIF LEFT$(Paths(i), j) <> LEFT$(Paths(0), j) THEN
          EXIT DO
        END IF
      ELSE
        j = INSTR(k, Paths(i), $PATH_SEPARATOR)
        IF j = 0 THEN
          EXIT DO
        END IF
      END IF
    NEXT i
    s = LEFT$(Paths(0), j + CLNG(k <> 1))
    k = j + 1
  LOOP
  FUNCTION = s

END FUNCTION

FUNCTION PBMAIN () AS LONG

' testing the above function

LOCAL s() AS STRING
LOCAL i AS LONG

REDIM s(0 TO 2)
ARRAY ASSIGN s() = "/home/user1/tmp/coverage/test", _
                   "/home/user1/tmp/covert/operator", _
                   "/home/user1/tmp/coven/members"
FOR i = 0 TO UBOUND(s()): CON.PRINT s(i): NEXT i
CON.PRINT CommonDirectoryPath(s()) & " <- common"
CON.PRINT

REDIM s(0 TO 3)
ARRAY ASSIGN s() = "/home/user1/tmp/coverage/test", _
                   "/home/user1/tmp/covert/operator", _
                   "/home/user1/tmp/coven/members", _
                   "/home/user1/abc/coven/members"
FOR i = 0 TO UBOUND(s()): CON.PRINT s(i): NEXT i
CON.PRINT CommonDirectoryPath(s()) & " <- common"
CON.PRINT

REDIM s(0 TO 2)
ARRAY ASSIGN s() = "/home/user1/tmp/coverage/test", _
                   "/hope/user1/tmp/covert/operator", _
                   "/home/user1/tmp/coven/members"
FOR i = 0 TO UBOUND(s()): CON.PRINT s(i): NEXT i
CON.PRINT CommonDirectoryPath(s()) & " <- common"
CON.PRINT

CON.PRINT "hit any key to end program"
CON.WAITKEY$

END FUNCTION


<#
.Synopsis
    Finds the deepest common directory path of files passed through the pipeline.
.Parameter File
    PowerShell file object.
#>
function Get-CommonPath {
[CmdletBinding()]
    param (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [System.IO.FileInfo] $File
    )
    process {
        # Get the current file's path list
        $PathList =  $File.FullName -split "\$([IO.Path]::DirectorySeparatorChar)"
        # Get the most common path list
        if ($CommonPathList) {
            $CommonPathList = (Compare-Object -ReferenceObject $CommonPathList -DifferenceObject $PathList -IncludeEqual `
                -ExcludeDifferent -SyncWindow 0).InputObject
        } else {
            $CommonPathList = $PathList
        }
    }
    end {
        $CommonPathList -join [IO.Path]::DirectorySeparatorChar
    }
}


%! directory_prefix(PATHs,STOP0,PREFIX)

directory_prefix([],_STOP0_,'')
:-
!
.

directory_prefix(PATHs0,STOP0,PREFIX)
:-
prolog:once(longest_prefix(PATHs0,STOP0,LONGEST_PREFIX)) ->
prolog:atom_concat(PREFIX,STOP0,LONGEST_PREFIX) ;
PREFIX=''
.

%! longest_prefix(PATHs,STOP0,PREFIX)

longest_prefix(PATHs0,STOP0,PREFIX)
:-
QUERY=(shortest_prefix(PATHs0,STOP0,SHORTEST_PREFIX)) ,
prolog:findall(SHORTEST_PREFIX,QUERY,SHORTEST_PREFIXs) ,
lists:reverse(SHORTEST_PREFIXs,LONGEST_PREFIXs) ,
lists:member(PREFIX,LONGEST_PREFIXs)
.

%! shortest_prefix(PATHs,STOP0,PREFIX)

shortest_prefix([],_STOP0_,_PREFIX_) .

shortest_prefix([PATH0|PATHs0],STOP0,PREFIX)
:-
starts_with(PATH0,PREFIX) ,
ends_with(PREFIX,STOP0) ,
shortest_prefix(PATHs0,STOP0,PREFIX)
.

%! starts_with(TARGET,START)

starts_with(TARGET,START)
:-
prolog:atom_concat(START,_,TARGET)
.

%! ends_with(TARGET,END)

ends_with(TARGET,END)
:-
prolog:atom_concat(_,END,TARGET)
.


Procedure.s CommonPath(Array InPaths.s(1),separator.s="/")
  Protected SOut$=""
  Protected i, j, toggle

  If ArraySize(InPaths())=0
    ProcedureReturn InPaths(0)  ; Special case, only one path
  EndIf

  Repeat
    i+1
    toggle=#False
    For j=1 To ArraySize(InPaths())
      If (StringField(InPaths(j-1),i,separator)=StringField(InPaths(j),i,separator))
        If Not toggle
          SOut$+StringField(InPaths(j-1),i,separator)+separator
          toggle=#True
        EndIf
      Else
        ProcedureReturn SOut$
      EndIf
    Next
  ForEver
EndProcedure


>>> import os
>>> os.path.commonpath(['/home/user1/tmp/coverage/test',
                        '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp'


get_common_dir <- function(paths, delim = "/")
{
  path_chunks <- strsplit(paths, delim)

  i <- 1
  repeat({
    current_chunk <- sapply(path_chunks, function(x) x[i])
    if(any(current_chunk != current_chunk[1])) break
    i <- i + 1
  })
  paste(path_chunks[[1]][seq_len(i - 1)], collapse = delim)

}

# Example Usage:
paths <- c(
  '/home/user1/tmp/coverage/test',
  '/home/user1/tmp/covert/operator',
  '/home/user1/tmp/coven/members')

get_common_dir(paths)           # "/home/user1/tmp"


#lang racket

(define (common-directory path . paths)
  (string-join
   (let loop ([path  (string-split path "/" #:trim? #f)]
              [paths (map (λ(p) (string-split p "/" #:trim? #f)) paths)])
     (if (and (pair? path)
              (andmap (λ(p) (and (pair? p) (equal? (car p) (car path))))
                      paths))
       (cons (car path) (loop (cdr path) (map cdr paths)))
       '()))
   "/"))

(common-directory
 "/home/user1/tmp/coverage/test"
 "/home/user1/tmp/covert/operator"
 "/home/user1/tmp/coven/members")
;; --> "/home/user1/tmp"


my $sep = '/';
my @dirs = </home/user1/tmp/coverage/test
            /home/user1/tmp/covert/operator
            /home/user1/tmp/coven/members>;

my @comps = @dirs.map: { [ .comb(/ $sep [ <!before $sep> . ]* /) ] };

my $prefix = '';

while all(@comps[*]»[0]) eq @comps[0][0] {
    $prefix ~= @comps[0][0] // last;
    @comps».shift;
}

say "The longest common path is $prefix";


/*REXX program  finds  the  common directory path  for a list of files.                 */
          @.  =                                  /*the default for all file lists (null)*/
          @.1 = '/home/user1/tmp/coverage/test'
          @.2 = '/home/user1/tmp/covert/operator'
          @.3 = '/home/user1/tmp/coven/members'
L= length(@.1)                                   /*use the length of the first string.  */
                 do j=2  while  @.j\==''         /*start search with the second string. */
                 _= compare(@.j, @.1)            /*use REXX  compare  BIF for comparison*/
                 if _==0  then iterate           /*Strings are equal? Then con't use min*/
                 L= min(L, _)                    /*get the minimum length equal strings.*/
                 if right(@.j, 1)=='/'  then iterate  /*if a directory,  then it's OK.  */
                 L= lastpos('/', left(@.j, L) )       /*obtain directory name up to here*/
                 end   /*j*/

common= left( @.1, lastpos('/', @.1, L) )        /*determine the shortest  DIR  string. */
if right(common, 1)=='/'  then common= left(common, max(0, length(common) - 1) )
if common==''  then common= "/"                  /*if no common directory, assume home. */
say 'common directory path: '  common            /* [↑]  handle trailing   /   delimiter*/
                                                 /*stick a fork in it,  we're all done. */


# Project : Find common directory path

load "stdlib.ring"
i = null
o = null
path = list(3)

path[1] = "/home/user1/tmp/coverage/test"
path[2] = "/home/user1/tmp/covert/operator"
path[3] = "/home/user1/tmp/coven/members"

see commonpath(path, "/")

func commonpath(p, s)
while i != 0
      o = i
      i = substring(p[1], s, i+1)
      for j = 2 to len(p)
          if left(p[1], i) != left(p[j], i)
             exit 2
          ok
      next
end
return left(p[1], o-1)


require 'abbrev'

dirs = %w( /home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members )

common_prefix = dirs.abbrev.keys.min_by {|key| key.length}.chop  # => "/home/user1/tmp/cove"
common_directory = common_prefix.sub(%r{/[^/]*$}, '')            # => "/home/user1/tmp"


' ------------------------------------------
' Find common directory to all directories
' and directories common with other Paths
' ------------------------------------------
print word$(word$(httpget$("http://tycho.usno.navy.mil/cgi-bin/timer.pl"),1,"UTC"),2,"
") ' Universal time

dim path$(20)
path$(1)	= "/home/user1/tmp/coverage/test"
path$(2)	= "/home/user1/tmp/covert/operator"
path$(3)	= "/home/user1/tmp/coven/members"

path$(4)	= "/home/user1/tmp1/coverage/test"
path$(5)	= "/home/user1/tmp1/covert/operator"
path$(6)	= "/home/user1/tmp1/coven/members"

path$(7)	= "/home/user1/tmp2/coverage/test"
path$(8)	= "/home/user1/tmp2/covert/operator"
path$(9)	= "/home/user1/tmp2/coven/members"

path$(10)	= "/home/user1/tmp3/coverage/test"
path$(11)	= "/home/user1/tmp3/covert/operator"
path$(12)	= "/home/user1/tmp3/coven/members"

sqliteconnect #mem, ":memory:"
#mem execute("CREATE TABLE dirTree (seq,pos,dir)")

for i = 1 to 12
j = 1
[loop]
j 	= instr(path$(i),"/",j + 1)
if j > 0 then
	dir$	= mid$(path$(i),1,j)
	mem$	= "INSERT INTO dirTree VALUES (";i;",";j;",'";dir$;"')"
	#mem execute(mem$)
	goto [loop]
end if
next i

mem$ = "SELECT	dir FROM dirTree GROUP BY dir HAVING count(*) = pos ORDER BY pos desc LIMIT 1"
#mem execute(mem$)
rows = #mem ROWCOUNT()		'Get the number of rows
if rows > 0 then
	#row = #mem #nextrow()
	print "====== Largest Directory Common to all Paths ========="
	print #row dir$()
    else
	print "No common Directory"
end if

html "
"

print "========= Common paths ================"

mem$ = "SELECT t.seq as seq,t.pos as pos,t.dir as dir,t1.seq as t1Seq ,t1.dir as t1Dir
FROM	dirTree as t
JOIN	dirTree as t1
ON	t1.dir = t.dir
AND	t1.seq > t.seq
GROUP BY t.dir,t1.seq"

html "

Seq
Path
Common Dir
Seq
With Path
"

#mem execute(mem$)
WHILE   #mem hasanswer()
	#row 	= #mem #nextrow()
	seq	= #row seq()
	t1Seq	= #row t1Seq()
	pos	= #row pos()
	dir$	= #row dir$()
	t1Dir$	= #row t1Dir$()
html "
"
html "";seq;"	"
html "";path$(seq);"	"
html "";dir$;"	"
html "";t1Seq;"	"
html "";path$(t1Seq);"	"
html "
"
WEND
html "
"
wait
end


use std::path::{Path, PathBuf};

fn main() {
    let paths = [
        Path::new("/home/user1/tmp/coverage/test"),
        Path::new("/home/user1/tmp/covert/operator"),
        Path::new("/home/user1/tmp/coven/members"),
    ];
    match common_path(&paths) {
        Some(p) => println!("The common path is: {:#?}", p),
        None => println!("No common paths found"),
    }
}

fn common_path<I, P>(paths: I) -> Option<PathBuf>
where
    I: IntoIterator<Item = P>,
    P: AsRef<Path>,
{
    let mut iter = paths.into_iter();
    let mut ret = iter.next()?.as_ref().to_path_buf();
    for path in iter {
        if let Some(r) = common(ret, path.as_ref()) {
            ret = r;
        } else {
            return None;
        }
    }
    Some(ret)
}

fn common<A: AsRef<Path>, B: AsRef<Path>>(a: A, b: B) -> Option<PathBuf> {
    let a = a.as_ref().components();
    let b = b.as_ref().components();
    let mut ret = PathBuf::new();
    let mut found = false;
    for (one, two) in a.zip(b) {
        if one == two {
            ret.push(one);
            found = true;
        } else {
            break;
        }
    }
    if found {
        Some(ret)
    } else {
        None
    }
}


object FindCommonDirectoryPath extends App {
  def commonPath(paths: List[String]): String = {
    def common(a: List[String], b: List[String]): List[String] = (a, b) match {
      case (a :: as, b :: bs) if a equals b => a :: common(as, bs)
      case _ => Nil
    }
    if (paths.length < 2) paths.headOption.getOrElse("")
    else paths.map(_.split("/").toList).reduceLeft(common).mkString("/")
  }

  val test = List(
    "/home/user1/tmp/coverage/test",
    "/home/user1/tmp/covert/operator",
    "/home/user1/tmp/coven/members"
  )
  println(commonPath(test))
}


$ include "seed7_05.s7i";

const func integer: commonLen (in array string: names, in char: sep) is func
  result
    var integer: result is -1;
  local
    var integer: index is 0;
    var integer: pos is 1;
  begin
    if length(names) <> 0 then
      repeat
        for index range 1 to length(names) do
          if pos > length(names[index]) or names[index][pos] <> names[1][pos] then
            decr(pos);
            while pos >= 1 and names[1][pos] <> sep do
              decr(pos);
            end while;
            if pos > 1 then
              decr(pos);
            end if;
            result := pos;
          end if;
        end for;
        incr(pos);
      until result <> -1;
    end if;
  end func;

const proc: main is func
  local
    var integer: length is 0;
    const array string: names is [] ("/home/user1/tmp/coverage/test",
                                     "/home/user1/tmp/covert/operator",
                                     "/home/user1/tmp/coven/members")
  begin
    length := commonLen(names, '/');
    if length = 0 then
      writeln("No common path");
    else
      writeln("Common path: " <& names[1][.. length]);
    end if;
  end func;


var dirs = %w(
    /home/user1/tmp/coverage/test
    /home/user1/tmp/covert/operator
    /home/user1/tmp/coven/members
);

var unique_pref = dirs.map{.split('/')}.abbrev.min_by{.len};
var common_dir  = [unique_pref, unique_pref.pop][0].join('/');
say common_dir;   # => /home/user1/tmp


fun takeWhileEq ([], _) = []
  | takeWhileEq (_, []) = []
  | takeWhileEq (x :: xs, y :: ys) =
      if x = y then x :: takeWhileEq (xs, ys) else []

fun commonPath sep =
  let
    val commonInit = fn [] => [] | x :: xs => foldl takeWhileEq x xs
    and split = String.fields (fn c => c = sep)
    and join = String.concatWith (str sep)
  in
    join o commonInit o map split
  end

val paths = [
  "/home/user1/tmp/coverage/test",
  "/home/user1/tmp/covert/operator",
  "/home/user1/tmp/coven/members"
]

val () = print (commonPath #"/" paths ^ "\n")


import Foundation

func getPrefix(_ text:[String]) -> String? {
    var common:String = text[0]
    for i in text {
        common = i.commonPrefix(with: common)
    }
    return common
}

var test = ["/home/user1/tmp/coverage/test",
 "/home/user1/tmp/covert/operator",
 "/home/user1/tmp/coven/members"]

var output:String = getPrefix(test)!
print(output)


package require Tcl 8.5
proc pop {varname} {
    upvar 1 $varname var
    set var [lassign $var head]
    return $head
}

proc common_prefix {dirs {separator "/"}} {
    set parts [split [pop dirs] $separator]
    while {[llength $dirs]} {
        set r {}
        foreach cmp $parts elt [split [pop dirs] $separator] {
            if {$cmp ne $elt} break
            lappend r $cmp
        }
        set parts $r
    }
    return [join $parts $separator]
}


$$ MODE TUSCRIPT
common=""
dir1="/home/user1/tmp/coverage/test"
dir2="/home/user1/tmp/covert/operator"
dir3="/home/user1/tmp/coven/members"
dir1=SPLIT (dir1,":/:"),dir2=SPLIT (dir2,":/:"), dir3=SPLIT (dir3,":/:")
LOOP d1=dir1,d2=dir2,d3=dir3
 IF (d1==d2,d3) THEN
  common=APPEND(common,d1,"/")
 ELSE
  PRINT common
  EXIT
 ENDIF
ENDLOOP


#!/bin/sh

pathlist='/home/user1/tmp/coverage/test
/home/user1/tmp/covert/operator
/home/user1/tmp/coven/members'

i=2

while [ $i -lt 100 ]
do
  path=`echo "$pathlist" | cut -f1-$i -d/ | uniq -d`
  if [ -z "$path" ]
  then
     echo $prev_path
     break
  else
     prev_path=$path
  fi
  i=`expr $i + 1`
done


#import std

comdir"s" "p" = mat"s" reduce(gcp,0) (map sep "s") "p"


' Read the list of paths (newline-separated) into an array...
strPaths = Split(WScript.StdIn.ReadAll, vbCrLf)

' Split each path by the delimiter (/)...
For i = 0 To UBound(strPaths)
	strPaths(i) = Split(strPaths(i), "/")
Next

With CreateObject("Scripting.FileSystemObject")

	' Test each path segment...
	For j = 0 To UBound(strPaths(0))

		' Test each successive path against the first...
		For i = 1 To UBound(strPaths)
			If strPaths(0)(j) <> strPaths(i)(j) Then Exit For
		Next

		' If we didn't make it all the way through, exit the block...
		If i <= UBound(strPaths) Then Exit For

		' Make sure this path exists...
		If Not .FolderExists(strPath & strPaths(0)(j) & "/") Then Exit For
		strPath = strPath & strPaths(0)(j) & "/"

	Next

End With

' Remove the final "/"...
WScript.Echo Left(strPath, Len(strPath) - 1)


Public Function CommonDirectoryPath(ParamArray Paths()) As String
Dim v As Variant
Dim Path() As String, s As String
Dim i As Long, j As Long, k As Long
Const PATH_SEPARATOR As String = "/"

  For Each v In Paths
    ReDim Preserve Path(0 To i)
    Path(i) = v
    i = i + 1
  Next v

  k = 1

  Do
    For i = 0 To UBound(Path)
      If i Then
        If InStr(k, Path(i), PATH_SEPARATOR) <> j Then
          Exit Do
        ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then
          Exit Do
        End If
      Else
        j = InStr(k, Path(i), PATH_SEPARATOR)
        If j = 0 Then
          Exit Do
        End If
      End If
    Next i
    s = Left$(Path(0), j + CLng(k <> 1))
    k = j + 1
  Loop
  CommonDirectoryPath = s

End Function

Sub Main()

' testing the above function

Debug.Assert CommonDirectoryPath( _
 "/home/user1/tmp/coverage/test", _
 "/home/user1/tmp/covert/operator", _
 "/home/user1/tmp/coven/members") = _
 "/home/user1/tmp"

 Debug.Assert CommonDirectoryPath( _
 "/home/user1/tmp/coverage/test", _
 "/home/user1/tmp/covert/operator", _
 "/home/user1/tmp/coven/members", _
 "/home/user1/abc/coven/members") = _
 "/home/user1"

Debug.Assert CommonDirectoryPath( _
 "/home/user1/tmp/coverage/test", _
 "/hope/user1/tmp/covert/operator", _
 "/home/user1/tmp/coven/members") = _
 "/"

End Sub


var findCommonDir = Fn.new { |paths, sep|
    var count = paths.count
    if (count == 0) return ""
    if (count == 1) return paths[0]
    var splits = List.filled(count, null)
    for (i in 0...count) splits[i] = paths[i].split(sep)
    var minLen = splits[0].count
    for (i in 1...count) {
        var c = splits[i].count
        if (c < minLen) minLen = c
    }
    if (minLen < 2) return ""
    var common = ""
    for (i in 1...minLen) {
        var dir = splits[0][i]
        for (j in 1...count) {
            if (splits[j][i] != dir) return common
        }
        common = common + sep + dir
    }
    return common
}

var paths = [
    "/home/user1/tmp/coverage/test",
    "/home/user1/tmp/covert/operator",
    "/home/user1/tmp/coven/members"
]
System.write("The common directory path is: ")
System.print(findCommonDir.call(paths, "/"))


x$ = "/home/user1/tmp/coverage/test"
y$ = "/home/user1/tmp/covert/operator"
z$ = "/home/user1/tmp/coven/members"

a = len(x$)
if a > len(y$)  a = len(y$)
if a > len(z$)  a = len(z$)
for i = 1 to a
    if mid$(x$, i, 1) <> mid$(y$, i, 1)  break
next i
a = i - 1

for i = 1 to a
    if mid$(x$, i, 1) <> mid$(z$, i, 1)  break
next i
a = i - 1

if mid$(x$, i, 1) <> "/" then
    for i = a to 1 step -1
        if "/" = mid$(x$, i, 1)  break
    next i
fi

REM Task description says no trailing slash, so...
a = i - 1
print "Common path is '", left$(x$, a), "'"


dirs:=T("/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator",
        "/home/user1/tmp/coven/members");
n:=Utils.zipWith('==,dirs.xplode()).find(False); // character pos which differs
n=dirs[0][0,n].rfind("/");  // find last "/"
dirs[0][0,n];


V size1 = fs:file_size(‘input.txt’)
V size2 = fs:file_size(‘/input.txt’)


putch:	equ	2	; Print character
puts:	equ	9	; Print $-terminated string
setdta:	equ	1Ah	; Set DTA
stat:	equ	4Eh	; Get file info
	cpu	8086
	bits	16
	org	100h
section	.text
	mov	si,curf		; Print file size for 'INPUT.TXT'
	call	pfsize		; (in current directory),
	mov	si,rootf	; Then for '\INPUT.TXT' in root directory
	;;;	Print file name and size for file in DS:SI
pfsize:	mov	ah,setdta	; Set disc transfer area pointer
	mov	dx,dta
	int	21h
	call	puts0		; Print the filename in SI
	mov	ah,puts		; Print colon and space
	mov	dx,colspc
	int	21h
	mov	ah,stat		; Find file info
	xor	cx,cx		; We want a normal file
	mov	dx,si		; Filename is in SI
	int	21h
	jnc	.ok		; Carry clear = found
	mov	ah,puts		; Carry set = not found = print 'not found'
	mov	dx,nofile
	int	21h
	ret
.ok:	les	bp,[dta+26]	; 32-bit file size in bytes at DTA+26
	mov	di,es		; DI:BP = 32-bit file size
	mov	bx,numbuf	; ASCII number buffer
	mov	cx,10		; Divisor (10)
.dgt:	xor	dx,dx		; 32-bit division (to get digits)
	mov	ax,di		; can be done with chained DIVs
	div	cx
	mov	di,ax
	mov	ax,bp
	div	cx
	mov	bp,ax
	add	dl,'0'		; DX is now remainder, i.e. digit
	dec	bx		; Move digit pointer backwards,
	mov	[bx],dl		; Store ASCII digit,
	or	ax,di		; If the new divisor is not zero,
	jnz	.dgt		; then there is another digit.
	mov	ah,puts		; If so, the number is done,
	mov	dx,bx		; and we can print it.
	int	21h
	ret
	;;;	Print 0-terminated string in SI
puts0:	push	si		; Save SI register
	mov	ah,putch	; Print char syscall
.loop:	lodsb			; Load character from SI
	test	al,al		; If zero,
	jz	.out		; then stop.
	mov	dl,al		; Tell DOS to print character
	int	21h
	jmp	.loop		; go get another.
.out:	pop	si		; Restore SI register
	ret
section	.data
rootf:	db	'\'		; \INPUT.TXT (for root) and
curf:	db	'INPUT.TXT',0	; INPUT.TXT (for current directory)
nofile:	db	'Not found.',13,10,'$'	; "Not found" message
	db	'0000000000'	; Number output buffer
numbuf:	db	' bytes',13,10,'$'
colspc:	db	': $'		; Colon and space
section	.bss
dta:	resb	512		; Disc transfer area


INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit

PROC Dir(CHAR ARRAY filter)
  BYTE dev=[1]
  CHAR ARRAY line(255)

  Close(dev)
  Open(dev,filter,6)
  DO
    InputSD(dev,line)
    PrintE(line)
    IF line(0)=0 THEN
      EXIT
    FI
  OD
  Close(dev)
RETURN

CARD FUNC FileSize(CHAR ARRAY src,dst)
  DEFINE BUF_LEN="100"
  BYTE dev=[1]
  BYTE ARRAY buff(BUF_LEN)
  CARD len,size

  size=0
  Close(dev)
  Open(dev,src,4)
  DO
    len=Bget(dev,buff,BUF_LEN)
    size==+len
  UNTIL len#BUF_LEN
  OD
  Close(dev)
RETURN (size)

PROC Main()
  CHAR ARRAY filter="D:*.*", fname="D:INPUT.TXT"
  CARD size

  Put(125) PutE() ;clear screen

  PrintF("Dir ""%S""%E",filter)
  Dir(filter)

  size=FileSize(fname)
  PrintF("Size of ""%S"" is %U bytes%E",fname,size)
RETURN


with Ada.Directories;  use Ada.Directories;
with Ada.Text_IO;      use Ada.Text_IO;

procedure Test_File_Size is
begin
   Put_Line (File_Size'Image (Size ("input.txt")) & " bytes");
   Put_Line (File_Size'Image (Size ("/input.txt")) & " bytes");
end Test_File_Size;


o_(stat("input.txt", ST_SIZE), "\n");
o_("/Cygwin.ico".stat(ST_SIZE), "\n");


PROC set = (REF FILE file,  INT page, line, character)VOID: ~


print volume "input.txt"
print volume "/input.txt"


FileGetSize, FileSize, input.txt  ; Retrieve the size in bytes.
MsgBox, Size of input.txt is %FileSize% bytes
FileGetSize, FileSize, \input.txt, K  ; Retrieve the size in Kbytes.
MsgBox, Size of \input.txt is %FileSize% Kbytes


@load "filefuncs"
function filesize(name         ,fd) {
    if ( stat(name, fd) == -1)
      return -1  # doesn't exist
    else
      return fd["size"]
}
BEGIN {
    print filesize("input.txt")
    print filesize("/input.txt")
}


If GetCalc("appvINPUT")→I
 Disp {I-2}ʳ▶Dec,i
Else
 Disp "NOT FOUND",i
End


' file size
' Return the entire message, FILELEN returns a NUMBER
FUNCTION printlen$(STRING name$)
    IF FILEEXISTS(name$) THEN
        RETURN name$ & ": " & STR$(FILELEN(name$))
    ELSE
        RETURN "file " & name$ & " not found"
    END IF
END FUNCTION

PRINT printlen$("input.txt")
PRINT printlen$("/input.txt")


@echo off
if not exist "%~1" exit /b 1 & rem If file doesn't exist exit with error code of 1.
for /f %%i in (%~1) do echo %~zi
pause>nul


      file% = OPENIN(@dir$+"input.txt")
      IF file% THEN
        PRINT "File size = " ; EXT#file%
        CLOSE #file%
      ENDIF

      file% = OPENIN("\input.txt")
      IF file% THEN
        PRINT "File size = " ; EXT#file%
        CLOSE #file%
      ENDIF


(getFileSize=
  size
.     fil$(!arg,rb)     {read in binary mode}
    & fil$(,END)        {seek to end of file}
    & fil$(,TEL):?size  {tell where we are}
    & fil$(,SET,-1)     {seeking to an impossible position closes the file, and fails}
  | !size               {return the size}
);

getFileSize$"valid.bra"
113622

getFileSize$"c:\\boot.ini"
211


#include <stdlib.h>
#include <stdio.h>

long getFileSize(const char *filename)
{
  long result;
  FILE *fh = fopen(filename, "rb");
  fseek(fh, 0, SEEK_END);
  result = ftell(fh);
  fclose(fh);
  return result;
}

int main(void)
{
  printf("%ld\n", getFileSize("input.txt"));
  printf("%ld\n", getFileSize("/input.txt"));
  return 0;
}


using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(new FileInfo("/input.txt").Length);
        Console.WriteLine(new FileInfo("input.txt").Length);
    }
}


#include <iostream>
#include <fstream>

std::ios::off_type getFileSize(const char *filename) {
  std::ifstream f(filename);
  std::ios::pos_type begin = f.tellg();
  f.seekg(0, std::ios::end);
  std::ios::pos_type end = f.tellg();
  return end - begin;
}

int main() {
  std::cout << getFileSize("input.txt") << std::endl;
  std::cout << getFileSize("/input.txt") << std::endl;
  return 0;
}


import StdEnv

fileSize fileName world
    # (ok, file, world) = fopen fileName FReadData world
    | not ok = abort "Cannot open file"
    # (ok, file) = fseek file 0 FSeekEnd
    | not ok = abort "Cannot seek file"
    # (size, file) = fposition file
      (_, world) = fclose file world
    = (size, world)

Start world = fileSize "input.txt" world


(require '[clojure.java.io :as io])
(defn show-size [filename]
  (println filename "size:" (.length (io/file filename))))

(show-size "input.txt")
(show-size "/input.txt")


       identification division.
       program-id. FileInfo.

       data division.
       working-storage section.
       01  file-name              pic x(256).
       01  file-size-edited       pic zzz,zzz,zzz.
       01  file-details.
           05 file-size           pic x(8) comp-x.
           05 file-date.
              10 file-day         pic x comp-x.
              10 file-month       pic x comp-x.
              10 file-year        pic xx comp-x.
           05 file-time.
              10 file-hour        pic x comp-x.
              10 file-minute      pic x comp-x.
              10 file-second      pic x comp-x.
              10 file-hundredths  pic x comp-x.

       procedure division.
       main.
           move "input.txt" to file-name
           perform file-info

           move "\input.txt" to file-name
           perform file-info

           stop run
           .

       file-info.
           call "CBL_CHECK_FILE_EXIST"
              using file-name, file-details
              returning return-code
           if return-code = 0
              move file-size to file-size-edited
              display function trim(file-name) " "
                      function trim(file-size-edited) " Bytes"
           else
              display function trim(file-name) " not found!"
           end-if
           .


<cfscript>
  localFile = getFileInfo(expandpath("input.txt"));
  rootFile = getFileInfo("/input.txt");
</cfscript>

<cfoutput>
  Size of input.txt is #localFile.size# bytes.
  Size of /input.txt is #rootFile.size# bytes.
</cfoutput>


(with-open-file (stream (make-pathname :name "input.txt")
                 :direction :input
                 :if-does-not-exist nil)
  (print (if stream (file-length stream) 0)))

(with-open-file (stream (make-pathname :directory '(:absolute "") :name "input.txt")
                 :direction :input
                 :if-does-not-exist nil)
  (print (if stream (file-length stream) 0)))


import std.file, std.stdio, std.path, std.file, std.stream,
       std.mmfile;

void main() {
    immutable fileName = "file_size.exe";

    try {
        writefln("File '%s' has size:", fileName);

        writefln("%10d bytes by std.file.getSize (function)",
                 std.file.getSize(fileName));

        writefln("%10d bytes by std.stream (class)",
                 new std.stream.File(fileName).size);

        // mmfile can treat the file as an array in memory.
        writefln("%10d bytes by std.mmfile (class)",
                 new std.mmfile.MmFile(fileName).length);
    } catch (Exception e) {
        e.msg.writefln;
    }
}


program SizeOfFile;

{$APPTYPE CONSOLE}

uses SysUtils;

function CheckFileSize(const aFilename: string): Integer;
var
  lFile: file of Byte;
begin
  AssignFile(lFile, aFilename);
  FileMode := 0; {Access file in read only mode}
  Reset(lFile);
  Result := FileSize(lFile);
  CloseFile(lFile);
end;

begin
  Writeln('input.txt ', CheckFileSize('input.txt'));
  Writeln('\input.txt ', CheckFileSize('\input.txt'));
end.


for file in [<file:input.txt>, <file:///input.txt>] {
  println(`The size of $file is ${file.length()} bytes.`)
}


class
    APPLICATION
create
    make
feature {NONE} -- Initialization
    make
            -- Run application.
        do
            create input_file.make_open_read ("input.txt")
            print(input_file.count)
            print("%N")
            input_file.close
            create environment
            input_file.make_open_read(environment.root_directory_name + "input.txt")
            print(input_file.count)
            input_file.close
        end
feature -- Access
    input_file: PLAIN_TEXT_FILE
    environment:EXECUTION_ENVIRONMENT
end


import system'io;
import extensions;

public program()
{
    console.printLine(File.assign("input.txt").Length);

    console.printLine(File.assign("\input.txt").Length)
}


IO.puts File.stat!("input.txt").size
IO.puts File.stat!("/input.txt").size


(message "sizes are %s and %s"
         (nth 7 (file-attributes "input.txt"))
         (nth 7 (file-attributes "/input.txt")))


-module(file_size).
-export([file_size/0]).

-include_lib("kernel/include/file.hrl").

file_size() ->
    print_file_size("input.txt"),
    print_file_size("/input.txt").

print_file_size(Filename) ->
    case file:read_file_info(Filename) of
	{ok, FileInfo} ->
	    io:format("~s ~p~n", [Filename, FileInfo#file_info.size]);
	{error, _} ->
	    io:format("~s could not be opened~n",[Filename])
    end.


include file.e

function file_size(sequence file_name)
    object x
    x = dir(file_name)
    if sequence(x) and length(x) = 1 then
        return x[1][D_SIZE]
    else
        return -1 -- the file does not exist
    end if
end function

procedure test(sequence file_name)
    integer size
    size = file_size(file_name)
    if size < 0 then
        printf(1,"%s file does not exist.\n",{file_name})
    else
        printf(1,"%s size is %d.\n",{file_name,size})
    end if
end procedure

test("input.txt") -- in the current working directory
test("/input.txt") -- in the file system root


open NUnit.Framework
open FsUnit

[<Test>]
let ``Validate that the size of the two files is the same`` () =
  let local = System.IO.FileInfo(__SOURCE_DIRECTORY__ + "\input.txt")
  let root = System.IO.FileInfo(System.IO.Directory.GetDirectoryRoot(__SOURCE_DIRECTORY__) + "input.txt")
  local.Length = root.Length |> should be True


"input.txt" file-info size>> .
    1321
"file-does-not-exist.txt" file-info size>>
 "Unix system call ``stat'' failed:"...


#APPTYPE CONSOLE

PRINT FileLen("sync.log")
PRINT FileLen("\sync.log")
PAUSE


: .filesize ( addr len -- ) 2dup type ."  is "
  r/o open-file throw
  dup file-size throw  <# #s #> type ."  bytes long." cr
  close-file throw ;

 s" input.txt" .filesize
s" /input.txt" .filesize


    use :: iso_fortran_env, only : FILE_STORAGE_SIZE
    implicit none
    character(len=*),parameter :: filename(*)=[character(len=256) :: 'input.txt', '/input.txt']
    integer                    :: file_size, i
    do i=1,size(filename)
       INQUIRE(FILE=filename(i), SIZE=file_size)  ! return -1 if cannot determine file size
       write(*,*)'size of file '//trim(filename(i))//' is ',file_size * FILE_STORAGE_SIZE /8,' bytes'
    enddo
    end


' FB 1.05.0 Win64

#include "file.bi"

Print FileLen("input.txt"), FileLen(Environ("SystemRoot") + "\input.txt")
Sleep


println[newJava["java.io.File", "input.txt"].length[]]
println[newJava["java.io.File", "/input.txt"].length[]]


Public Sub Main()
Dim stInfo As Stat = Stat(User.home &/ "input.txt")
Dim stInfo1 As Stat = Stat("/input.txt")

Print User.Home &/ "input.txt = " & stInfo.Size & " bytes"
Print "/input.txt = " & stInfo1.Size & " bytes"

End


package main

import "fmt"
import "os"

func printFileSize(f string) {
    if stat, err := os.Stat(f); err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(stat.Size())
    }
}

func main() {
    printFileSize("input.txt")
    printFileSize("/input.txt")
}


println new File('index.txt').length();
println new File('/index.txt').length();


import System.IO

printFileSize filename = withFile filename ReadMode hFileSize >>= print

main = mapM_ printFileSize ["input.txt", "/input.txt"]


READ(FILE="input.txt", LENgth=bytes) ! bytes = -1 if not existent
READ(FILE="C:\input.txt", LENgth=bytes) ! bytes = -1 if not existent


every dir := !["./","/"] do {
   write("Size of ",f := dir || "input.txt"," = ",stat(f).size)  |stop("failure for to stat ",f)
   }


require 'files'
fsize 'input.txt';'/input.txt'


import java.io.File;

public class FileSize
{
    public static void main ( String[] args )
    {
        System.out.println("input.txt  : " + new File("input.txt").length() + " bytes");
        System.out.println("/input.txt : " + new File("/input.txt").length() + " bytes");
    }
}


var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.GetFile('input.txt').Size;
fso.GetFile('c:/input.txt').Size;


jq -Rs length input.txt

jq -Rs length /input.txt


// version 1.0.6

import java.io.File

fun main(args: Array<String>) {
    val paths = arrayOf("input.txt", "c:\\input.txt")
    for (path in paths)
        println("Length of $path is ${File(path).length()} bytes")
}


// local to current directory
local(f = file('input.txt'))
handle => { #f->close }
#f->size

// file at file system root
local(f = file('//input.txt'))
handle => { #f->close }
#f->size


'input.txt in current directory
OPEN DefaultDir$ + "/input.txt" FOR input AS #m
PRINT "File size: "; lof(#m)
CLOSE #m

'input.txt in root
OPEN "c:/input.txt" FOR input AS #m
PRINT "File size: "; lof(#m)
CLOSE #m


----------------------------------------
-- Returns file size
-- @param {string} filename
-- @return {integer}
----------------------------------------
on getFileSize (filename)
  fp = xtra("fileIO").new()
  fp.openFile(filename, 1)
  if fp.status() then return 0
  len = fp.getLength()
  fp.closeFile()
  return len
end


// root folder
set the defaultfolder to "/"
repeat for each line fline in (the detailed files)
    if item 1 of fline is "input.txt" then
        put item 2 of fline --bytes
        exit repeat
    end if
end repeat

// current working dir of stack
put the effective filename of this stack into tPath
set the itemDelimiter to slash
delete last item of tPath
set the defaultfolder to tPath
repeat for each line fline in (the detailed files)
    if item 1 of fline is "input.txt" then
        put item 2 of fline
        exit repeat
    end if
end repeat


function GetFileSize( filename )
    local fp = io.open( filename )
    if fp == nil then
 	return nil
    end
    local filesize = fp:seek( "end" )
    fp:close()
    return filesize
end


d1 = dir('input.txt');
d2 = dir('/input.txt');
fprintf('Size of input.txt is %d bytes\n', d1.bytes)
fprintf('Size of /input.txt is %d bytes\n', d2.bytes)


-- Returns filesize in bytes or 0 if the file is missing
getFileSize "index.txt"
getFileSize "\index.txt"


import java.io.File

puts File.new('file-size.mirah').length()
puts File.new("./#{File.separator}file-size.mirah").length()


echo -ag $file(input.txt).size bytes
echo -ag $file(C:\input.txt).size bytes


MODULE FSize EXPORTS Main;

IMPORT IO, Fmt, FS, File, OSError;

VAR fstat: File.Status;

BEGIN
  TRY
    fstat := FS.Status("input.txt");
    IO.Put("Size of input.txt: " & Fmt.LongInt(fstat.size) & "\n");
    fstat := FS.Status("/input.txt");
    IO.Put("Size of /input.txt: " & Fmt.LongInt(fstat.size) & "\n");
  EXCEPT
  | OSError.E => IO.Put("ERROR: Could not get file status.\n");
  END;
END FSize.


import Nanoquery.IO
println new(File, "input.txt").length()
println new(File, "/input.txt").length()


/* NetRexx */
options replace format comments java symbols binary

runSample(arg)
return

-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
method fileSize(fn) public static returns double
  ff = File(fn)
  fSize = ff.length()
  return fSize

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  parse arg files
  if files = '' then files = 'input.txt F docs D /input.txt F /docs D'
  loop while files.length > 0
    parse files fn ft files
    select case(ft.upper())
      when 'F' then do
        ft = 'File'
        end
      when 'D' then do
        ft = 'Directory'
        end
      otherwise do
        ft = 'File'
        end
      end
    sz = fileSize(fn)
    say ft ''''fn'''' sz 'bytes.'
    end

  return


(println (first (file-info "input.txt")))
(println (first (file-info "/input.txt")))


import os
echo getFileSize "input.txt"
echo getFileSize "/input.txt"


use IO;
...
File("input.txt")->Size()->PrintLine();
File("c:\input.txt")->Size()->PrintLine();


NSFileManager *fm = [NSFileManager defaultManager];

// Pre-OS X 10.5
NSLog(@"%llu", [[fm fileAttributesAtPath:@"input.txt" traverseLink:YES] fileSize]);

// OS X 10.5+
NSLog(@"%llu", [[fm attributesOfItemAtPath:@"input.txt" error:NULL] fileSize]);


let printFileSize filename =
  let ic = open_in filename in
  Printf.printf "%d\n" (in_channel_length ic);
  close_in ic ;;

printFileSize "input.txt" ;;
printFileSize "/input.txt" ;;


File new("input.txt") size println
File new("/input.txt") size println


Parse Version v
Say v
fid='test.txt'
x=sysfiletree(fid,a.)
Say a.0
Say a.1
Say left(copies('123456789.',10),length(a.1))
Parse Var a.1 20 size .
Say 'file size:' size
s=charin(fid,,1000)
Say length(s)
Say 'file' fid
'type' fid


declare
  [Path] = {Module.link ['x-oz://system/os/Path.ozf']}
in
  {Show {Path.size "input.txt"}}
  {Show {Path.size "/input.txt"}}


my $size1 = -s 'input.txt';
my $size2 = -s '/input.txt';


function file_size(sequence file_name)
object d = dir(file_name)
    if atom(d) or length(d)!=1 then return -1 end if
    return d[1][D_SIZE]
end function

procedure test(sequence file_name)
integer size = file_size(file_name)
    if size<0 then
        printf(1,"%s file does not exist.\n",{file_name})
    else
        printf(1,"%s size is %d.\n",{file_name,size})
    end if
end procedure

test("input.txt") -- in the current working directory
test("/input.txt") -- in the file system root


<?php
echo filesize('input.txt'), "\n";
echo filesize('/input.txt'), "\n";
?>


(println (car (info "input.txt")))
(println (car (info "/input.txt")))


import Stdio;

int main(){
   write(file_size("input.txt") + "\n");
   write(file_size("/input.txt") + "\n");
}


/* To obtain file size of files in root as well as from current directory. */

test: proc options (main);
   declare ch character (1);
   declare i fixed binary (31);
   declare in1 file record;

   /* Open a file in the root directory. */
   open file (in1) title ('//asd.log,type(fixed),recsize(1)');
   on endfile (in1) go to next1;
   do i = 0 by 1;
      read file (in1) into (ch);
   end;
next1:
   put skip list ('file size in root directory =' || trim(i));
   close file (in1);

   /* Open a file in the current dorectory. */
   open file (in1) title ('/asd.txt,type(fixed),recsize(1)');
   on endfile (in1) go to next2;
   do i = 0 by 1;
      read file (in1) into (ch);
   end;
next2:
   put skip list ('local file size=' || trim(i));
end test;


;;; prints file size in bytes
sysfilesize('input.txt') =>
sysfilesize('/input.txt') =>


with Ada.Directories;          use Ada.Directories;
with Ada.Text_IO;              use Ada.Text_IO;
with Ada.Calendar.Formatting;  use Ada.Calendar.Formatting;

procedure File_Time_Test is
begin
   Put_Line (Image (Modification_Time ("file_time_test.adb")));
end File_Time_Test;


(input.txt  ) print
(input.txt) status pop pop pop = pop
(/input.txt ) print
(/input.txt) status pop pop pop = pop


Get-ChildItem input.txt | Select-Object Name,Length
Get-ChildItem \input.txt | Select-Object Name,Length


Debug FileSize("input.txt")
Debug FileSize("/input.txt")


import os

size = os.path.getsize('input.txt')
size = os.path.getsize('/input.txt')


sizeinwd <- file.info('input.txt')[["size"]]
sizeinroot <- file.info('/input.txt')[["size"]]


PROC get output = (STRING cmd) VOID:
IF STRING sh cmd = " " + cmd + " ; 2>&1";
   STRING output;
   execve output ("/bin/sh", ("sh", "-c", sh cmd), "", output) >= 0
THEN print (output) FI;
get output ("rm -rf WTC_1");				CO Ensure file doesn't exist CO
get output ("touch WTC_1");				CO Create file CO
get output ("ls -l --time-style=full-iso WTC_1");	CO Display its last modified time CO
get output ("touch -t 200109111246.40 WTC_1");		CO Change its last modified time CO
get output ("ls -l --time-style=full-iso WTC_1")	CO Verify it changed CO


FileGetTime, OutputVar, output.txt
MsgBox % OutputVar
FileSetTime, 20080101, output.txt
FileGetTime, OutputVar, output.txt
MsgBox % OutputVar


#lang racket
(file-size "input.txt")
(file-size "/input.txt")


say 'input.txt'.IO.s;
say '/input.txt'.IO.s;


$INCLUDE "rapidq.inc"

DIM file AS QFileStream

FUNCTION fileSize(name$) AS Integer
    file.Open(name$, fmOpenRead)
    Result = file.Size
    file.Close
END FUNCTION

PRINT "Size of input.txt is "; fileSize("input.txt")
PRINT "Size of \input.txt is "; fileSize("\input.txt")


'input.txt'  status.size
'/input.txt' status.size


@load "filefuncs"
BEGIN {

    name = "input.txt"

    # display time
    stat(name, fd)
    printf("%s\t%s\n", name, strftime("%a %b %e %H:%M:%S %Z %Y", fd["mtime"]) )

    # change time
    cmd = "touch -t 201409082359.59 " name
    system(cmd)
    close(cmd)

}


      DIM ft{dwLowDateTime%, dwHighDateTime%}
      DIM st{wYear{l&,h&}, wMonth{l&,h&}, wDayOfWeek{l&,h&}, \
      \      wDay{l&,h&}, wHour{l&,h&}, wMinute{l&,h&}, \
      \      wSecond{l&,h&}, wMilliseconds{l&,h&} }

      REM File is assumed to exist:
      file$ = @tmp$ + "rosetta.tmp"

      REM Get and display the modification time:
      file% = OPENIN(file$)
      SYS "GetFileTime", @hfile%(file%), 0, 0, ft{}
      CLOSE #file%
      SYS "FileTimeToSystemTime", ft{}, st{}
      date$ = STRING$(16, CHR$0)
      time$ = STRING$(16, CHR$0)
      SYS "GetDateFormat", 0, 0, st{}, 0, date$, LEN(date$) TO N%
      date$ = LEFT$(date$, N%-1)
      SYS "GetTimeFormat", 0, 0, st{}, 0, time$, LEN(time$) TO N%
      time$ = LEFT$(time$, N%-1)
      PRINT date$ " " time$

      REM Set the modification time to the current time:
      SYS "GetSystemTime", st{}
      SYS "SystemTimeToFileTime", st{}, ft{}
      file% = OPENUP(file$)
      SYS "SetFileTime", @hfile%(file%), 0, 0, ft{}
      CLOSE #file%


size? %info.txt
size? %/info.txt
size? ftp://username:password@ftp.site.com/info.txt
size? http://rosettacode.org


>> size? %input.txt
== 39244
>> size? %/c/input.txt
== 39244


with files'
"input.txt" :R open &size sip close drop putn
"/input.txt" :R open &size sip close drop putn


#include <sys/stat.h>
#include <stdio.h>
#include <time.h>
#include <utime.h>

const char *filename = "input.txt";

int main() {
  struct stat foo;
  time_t mtime;
  struct utimbuf new_times;

  if (stat(filename, &foo) < 0) {
    perror(filename);
    return 1;
  }
  mtime = foo.st_mtime; /* seconds since the epoch */

  new_times.actime = foo.st_atime; /* keep atime unchanged */
  new_times.modtime = time(NULL);    /* set mtime to current time */
  if (utime(filename, &new_times) < 0) {
    perror(filename);
    return 1;
  }

  return 0;
}


using System;
using System.IO;

Console.WriteLine(File.GetLastWriteTime("file.txt"));
File.SetLastWriteTime("file.txt", DateTime.Now);


/*REXX program determines a file's size (by reading all the data) in current dir & root.*/
parse arg iFID .                                 /*allow the user specify the  file ID. */
if iFID=='' | iFID==","  then iFID='input.txt'   /*Not specified?  Then use the default.*/
say 'size of     'iFID   "="   fSize(iFID)         'bytes'      /*the current directory.*/
say 'size of \..\'iFID   "="   fSize('\..\'iFID)   'bytes'      /* "    root      "     */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fSize: parse arg f;   $=0;   do while chars(f)\==0;    $ = $ + length( charin( f, , 1e4) )
                             end   /*while*/;          call lineout f      /*close file.*/
       return $


See len(read('input.txt')) + nl
see len(read('/input.txt')) + nl


size = File.size('input.txt')
size = File.size('/input.txt')


#include <boost/filesystem/operations.hpp>
#include <ctime>
#include <iostream>

int main( int argc , char *argv[ ] ) {
   if ( argc != 2 ) {
      std::cerr << "Error! Syntax: moditime <filename>!\n" ;
      return 1 ;
   }
   boost::filesystem::path p( argv[ 1 ] ) ;
   if ( boost::filesystem::exists( p ) ) {
      std::time_t t = boost::filesystem::last_write_time( p ) ;
      std::cout << "On " << std::ctime( &t ) << " the file " << argv[ 1 ]
	 << " was modified the last time!\n" ;
      std::cout << "Setting the modification time to now:\n" ;
      std::time_t n = std::time( 0 ) ;
      boost::filesystem::last_write_time( p , n ) ;
      t = boost::filesystem::last_write_time( p ) ;
      std::cout << "Now the modification time is " << std::ctime( &t ) << std::endl ;
      return 0 ;
   } else {
      std::cout << "Could not find file " << argv[ 1 ] << '\n' ;
      return 2 ;
   }
}


(import '(java.io File)
        '(java.util Date))

(Date. (.lastModified (File. "output.txt")))
(Date. (.lastModified (File. "docs")))

(.setLastModified (File. "output.txt")
                  (.lastModified (File. "docs")))


print fileSize(DefaultDir$,"input.txt")  ' current default directory
print fileSize("","input.txt")       ' root directory

function fileSize(dir$,file$)
open dir$;"\";file$ FOR input as #f
fileSize = lof(#f)                   ' Length Of File
close #f
end function


use std::{env, fs, process};
use std::io::{self, Write};
use std::fmt::Display;

fn main() {
    let file_name = env::args().nth(1).unwrap_or_else(|| exit_err("No file name supplied", 1));
    let metadata = fs::metadata(file_name).unwrap_or_else(|e| exit_err(e, 2));

    println!("Size of file.txt is {} bytes", metadata.len());
}

#[inline]
fn exit_err<T: Display>(msg: T, code: i32) -> ! {
    writeln!(&mut io::stderr(), "Error: {}", msg).expect("Could not write to stdout");
    process::exit(code)
}

}


import java.io.File

object FileSize extends App {
  val name = "pg1661.txt"

  println(s"$name  : ${new File(name).length()} bytes")
  println(s"/$name : ${new File(s"${File.separator}$name").length()} bytes")
}


(define (file-size filename)
  (call-with-input-file filename (lambda (port)
    (let loop ((c (read-char port))
               (count 0))
      (if (eof-object? c)
          count
          (loop (read-char port) (+ 1 count)))))))

(file-size "input.txt")
(file-size "/input.txt")


$ include "seed7_05.s7i";

const proc: main is func
  begin
    writeln(fileSize("input.txt"));
    writeln(fileSize("/input.txt"));
  end func;


import std.stdio;
import std.file: getTimes, setTimes, SysTime;

void main() {
    auto fname = "unixdict.txt";
    SysTime fileAccessTime, fileModificationTime;
    getTimes(fname, fileAccessTime, fileModificationTime);
    writeln(fileAccessTime, "\n", fileModificationTime);
    setTimes(fname, fileAccessTime, fileModificationTime);
}


function GetModifiedDate(const aFilename: string): TDateTime;
var
  hFile: Integer;
  iDosTime: Integer;
begin
  hFile := FileOpen(aFilename, fmOpenRead);
  iDosTime := FileGetDate(hFile);
  FileClose(hFile);
  if (hFile = -1) or (iDosTime = -1) then raise Exception.Create('Cannot read file: ' + sFilename);
  Result := FileDateToDateTime(iDosTime);
end;

procedure ChangeModifiedDate(const aFilename: string; aDateTime: TDateTime);
begin
  FileSetDate(aFileName, DateTimeToFileDate(aDateTime));
end;


say (Dir.cwd  + %f'input.txt' -> size);
say (Dir.root + %f'input.txt' -> size);


(File newNamed: 'input.txt') fileInfo fileSize.
(File newNamed: '/input.txt') fileInfo fileSize.


(File name: 'input.txt') size printNl.
(File name: '/input.txt') size printNl.


val size = OS.FileSys.fileSize "input.txt" ;;
val size = OS.FileSys.fileSize "/input.txt" ;


file open f using input.txt, read binary
file seek f eof
file seek f query
display r(loc)
file close f


file size input.txt
file size /input.txt


def strdate(date) {
  return E.toString(<unsafe:java.util.makeDate>(date))
}

def test(type, file) {
    def t := file.lastModified()
    println(`The following $type called ${file.getPath()} ${
            if (t == 0) { "does not exist." } else { `was modified at ${strdate(t)}` }}`)
    println(`The following $type called ${file.getPath()} ${
            escape ne { file.setLastModified(timer.now(), ne); "was modified to current time." } catch _ { "does not exist." }}`)
    println(`The following $type called ${file.getPath()} ${
            escape ne { file.setLastModified(t, ne); "was modified to previous time." } catch _ { "does not exist." }}`)
}

test("file", <file:output.txt>)
test("directory", <file:docs>)


(nth 5 (file-attributes "input.txt")) ;; mod date+time

(set-file-times "input.txt") ;; to current-time
(set-file-times "input.txt"
                (encode-time 0 0 0  1 1 2014)) ;; to given date+time


-module( file_modification_time ).

-include_lib("kernel/include/file.hrl").

-export( [task/0] ).

task() ->
       File = "input.txt",
       {ok, File_info} = file:read_file_info( File ),
       io:fwrite( "Modification time ~p~n", [File_info#file_info.mtime] ),
       ok = file:write_file_info( File, File_info#file_info{mtime=calendar:local_time()} ).


" input.txt"  "R" file.open dup file.size . file.close
" /input.txt" "R" file.open dup file.size . file.close


%File = new FileObject();
%File.openForRead("input.txt");

while(!%File.isEOF())
{
	%Length += strLen(%File.readLine());
}

%File.close();
%File.delete();


$$ MODE TUSCRIPT
-- size of file input.txt
file="input.txt"
ERROR/STOP OPEN (file,READ,-std-)
file_size=BYTES ("input.txt")
ERROR/STOP CLOSE (file)

-- size of file x:/input.txt
ERROR/STOP OPEN (file,READ,x)
file_size=BYTES (file)
ERROR/STOP CLOSE (file)


size1=$(ls -l input.txt | tr -s ' ' | cut -d ' ' -f 5)
size2=$(ls -l /input.txt | tr -s ' ' | cut -d ' ' -f 5)


decl file f

f.open "input.txt"
out (size f) endl console
f.close

f.open "/input.txt"
out (size f) endl console
f.close


With CreateObject("Scripting.FileSystemObject")
	WScript.Echo .GetFile("input.txt").Size
	WScript.Echo .GetFile("\input.txt").Size
End With


open System
open System.IO

[<EntryPoint>]
let main args =
    Console.WriteLine(File.GetLastWriteTime(args.[0]))
    File.SetLastWriteTime(args.[0], DateTime.Now)
    0


' FB 1.05.0 Win64

' This example is taken directly from the FB documentation (see [http://www.freebasic.net/wiki/wikka.php?wakka=KeyPgFiledatetime])

#include "vbcompat.bi"  '' to use Format function

Dim filename As String, d As Double

Print "Enter a filename: "
Line Input filename

If FileExists(filename) Then
  Print "File last modified: ";
  d = FileDateTime( filename )
  Print Format( d, "yyyy-mm-dd hh:mm AM/PM" )
Else
  Print "File not found"
End If

Sleep


Option Explicit

----

Sub DisplayFileSize(ByVal Path As String, ByVal Filename As String)
Dim i As Long
  If InStr(Len(Path), Path, "\") = 0 Then
    Path = Path & "\"
  End If
  On Error Resume Next 'otherwise runtime error if file does not exist
  i = FileLen(Path & Filename)
  If Err.Number = 0 Then
    Debug.Print "file size: " & CStr(i) & " Bytes"
  Else
    Debug.Print "error: " & Err.Description
  End If
End Sub

----

Sub Main()
  DisplayFileSize CurDir(), "input.txt"
  DisplayFileSize CurDir(), "innputt.txt"
  DisplayFileSize Environ$("SystemRoot"), "input.txt"
End Sub


Dim local As New IO.FileInfo("input.txt")
Console.WriteLine(local.Length)

Dim root As New IO.FileInfo("\input.txt")
Console.WriteLine(root.Length)


import "io" for File

var name = "input.txt"
System.print("'%(name)' has a a size of %(File.size(name)) bytes")


; x86_64 linux nasm

section .data
localFileName: db "input.txt", 0
rootFileName: db "/initrd.img", 0

section .text

global _start

_start:

  ; open file in current dir
  mov rax, 2
  mov rdi, localFileName
  xor rsi, rsi
  mov rdx, 0
  syscall
  push rax

  mov rdi, rax ; file descriptior
  mov rsi, 0 ; offset
  mov rdx, 2 ; whence
  mov rax, 8 ; sys_lseek
  syscall

  ; compare result to actual size
  cmp rax, 11
  jne fail

  ; close the file
  pop rdi
  mov rax, 3
  syscall

  ; open file in root dir
  mov rax, 2
  mov rdi, rootFileName
  xor rsi, rsi
  mov rdx, 0
  syscall
  push rax

  mov rdi, rax ; file descriptior
  mov rsi, 0 ; offset
  mov rdx, 2 ; whence
  mov rax, 8 ; sys_lseek
  syscall

  ; compare result to actual size
  cmp rax, 37722243
  jne fail

  ; close the file
  pop rdi
  mov rax, 3
  syscall

  ; test successful
  mov rax, 60
  mov rdi, 0
  syscall

  ; test failed
  fail:
    mov rax, 60
    mov rdi, 1
    syscall


f = newJava["java.io.File", "FileModificationTime.frink"]
f.setLastModified[(#2022-01-01 5:00 AM# - #1970 UTC#) / ms]
println[f.lastModified[] ms + #1970 UTC#]


' There is no built in command in Gambas to 'set' the modification time of a file
' A shell call to 'touch' would do it

Public Sub Main()
Dim stInfo As Stat = Stat(User.home &/ "Rosetta.txt")

Print "Rosetta.txt was last modified " & Format(stInfo.LastModified, "dd/mm/yyy hh:nn:ss")

End


package main

import (
    "fmt"
    "os"
    "syscall"
    "time"
)

var filename = "input.txt"

func main() {
    foo, err := os.Stat(filename)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("mod time was:", foo.ModTime())
    mtime := time.Now()
    atime := mtime // a default, because os.Chtimes has an atime parameter.
    // but see if there's a real atime that we can preserve.
    if ss, ok := foo.Sys().(*syscall.Stat_t); ok {
        atime = time.Unix(ss.Atim.Sec, ss.Atim.Nsec)
    }
    os.Chtimes(filename, atime, mtime)
    fmt.Println("mod time now:", mtime)
}


proc ShowSize(FileName);
char FileName; int Size, C;
[Trap(false);           \disable abort on error
FSet(FOpen(FileName, 0), ^i);
Size:= 0;
repeat  C:= ChIn(3);    \reads 2 EOFs before
        Size:= Size+1;  \ read beyond end-of-file
until   GetErr;         \ is detected
IntOut(0, Size-2);
CrLf(0);
];

[ShowSize("input.txt");
 ShowSize("/input.txt"); \root under Linux
]


import System.Posix.Files
import System.Posix.Time

do status <- getFileStatus filename
   let atime = accessTime status
       mtime = modificationTime status -- seconds since the epoch
   curTime <- epochTime
   setFileTimes filename atime curTime -- keep atime unchanged
                                       -- set mtime to current time


CHARACTER timestamp*18

timestamp = ' ' ! blank timestamp will read:
SYSTEM(FIle="File_modification_time.hic", FileTime=timestamp) ! 20100320141940.525

timestamp = '19991231235950' ! set timestamp to Millenium - 10 seconds
SYSTEM(FIle="File_modification_time.hic", FileTime=timestamp)


every dir := !["./","/"] do {
   if i := stat(f := dir || "input.txt") then {
      write("info for ",f ," mtime= ",ctime(i.mtime),", atime=",ctime(i.ctime), ", atime=",ctime(i.atime))
      utime(f,i.atime,i.mtime-1024)
      i := stat(f)
      write("update for ",f ," mtime= ",ctime(i.mtime),", atime=",ctime(i.ctime), ", atime=",ctime(i.atime))
      }
   else stop("failure to stat ",f)
   }


   load 'files'
   fstamp 'input.txt'
2009 8 24 20 34 30


import java.io.File;
import java.util.Date;
public class FileModificationTimeTest {
   public static void test(String type, File file) {
       long t = file.lastModified();
       System.out.println("The following " + type + " called " + file.getPath() +
            (t == 0 ? " does not exist." : " was modified at " + new Date(t).toString() )
       );
       System.out.println("The following " + type + " called " + file.getPath() +
            (!file.setLastModified(System.currentTimeMillis()) ? " does not exist." : " was modified to current time." )
       );
       System.out.println("The following " + type + " called " + file.getPath() +
            (!file.setLastModified(t) ? " does not exist." : " was modified to previous time." )
       );
   }
   public static void main(String args[]) {
       test("file", new File("output.txt"));
       test("directory", new File("docs"));
   }
}


var fso = new ActiveXObject("Scripting.FileSystemObject");
var f = fso.GetFile('input.txt');
var mtime = f.DateLastModified;


/* File modification times, in Jsi */

var fileTime = File.mtime('fileModificationTime.jsi');
puts("Last mod time was: ", strftime(fileTime * 1000));

exec('touch fileModificationTime.jsi');

fileTime = File.mtime('fileModificationTime.jsi');
puts("Mod time now: ", strftime(fileTime * 1000));


using Dates

fname, _ = mktemp()

println("The modification time of $fname is ", Dates.unix2datetime(mtime(fname)))
println("\nTouch this file.")
touch(fname)
println("The modification time of $fname is now ", Dates.unix2datetime(mtime(fname)))


// version 1.0.6

import java.io.File

fun main(args: Array<String>) {
    val filePath = "input.txt" // or whatever
    val file = File(filePath)
    with (file) {
        println("%tc".format(lastModified()))
        // update to current time, say
        setLastModified(System.currentTimeMillis())
        println("%tc".format(lastModified()))
    }
}


local(f) = file('input.txt')
handle => { #f->close }
#f->modificationDate->format('%-D %r')
// result: 12/2/2010 11:04:15 PM


require "lfs"
local attributes = lfs.attributes("input.txt")
if attributes then
    print(path .. " was last modified " .. os.date("%c", attributes.modification) .. ".")

    -- set access and modification time to now ...
    lfs.touch("input.txt")

    -- ... or set modification time to now, keep original access time
    lfs.touch("input.txt", attributes.access, os.time())
else
    print(path .. " does not exist.")
end


Module CheckIt {
      \\ without *for wide output*  we open for ANSI (1 byte per character)
      \\ but here we need it only for the creation of a file
      Open "afile" for output as #f
      Close #f
      Print file.stamp("afile")   'it is a number in VB6 date format.
      \\ day format as for Greece
      Print Str$(File.Stamp("afile"),"hh:nn:ss dd/mm/yyyy") , "utc write time - by default"
      Print Str$(File.Stamp("afile" ,1),"hh:nn:ss dd/mm/yyyy") , "utc write time, 1"
      Print  Str$(File.Stamp("afile" ,-1),"hh:nn:ss dd/mm/yyyy"), "local write time, -1"
      Print Str$(File.Stamp("afile" ,2),"hh:nn:ss dd/mm/yyyy"), "utc creation time, 2"
      Print  Str$(File.Stamp("afile" ,-2),"hh:nn:ss dd/mm/yyyy"), "local creation time, -2"
}
Checkit


   f = dir('output.txt');  % struct f contains file information
   f.date     % is string containing modification time
   f.datenum  % numerical format (number of days)
   datestr(f.datenum)   % is the same as f.date
   % see also: stat, lstat


-- Returns a string containing the mod date for the file, e.g. "1/29/99 1:52:05 PM"
getFileModDate "C:\myFile.txt"


MODULE ModTime EXPORTS Main;

IMPORT IO, Fmt, File, FS, Date, OSError;

TYPE dateArray = ARRAY [0..5] OF TEXT;

VAR
  file: File.Status;
  date: Date.T;

PROCEDURE DateArray(date: Date.T): dateArray =
  BEGIN
    RETURN
      dateArray{Fmt.Int(date.year), Fmt.Int(ORD(date.month) + 1), Fmt.Int(date.day),
                Fmt.Int(date.hour), Fmt.Int(date.minute), Fmt.Int(date.second)};
  END DateArray;

BEGIN
  TRY
    file := FS.Status("test.txt");
    date := Date.FromTime(file.modificationTime);
    IO.Put(Fmt.FN("%s-%02s-%02s %02s:%02s:%02s", DateArray(date)));
    IO.Put("\n");
  EXCEPT
  | OSError.E => IO.Put("Error: Failed to get file status.\n");
  END;
END ModTime.


/* NetRexx */
options replace format comments java crossref symbols binary

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
  parse arg fileName
  if fileName = '' then fileName = 'data/tempfile01'
  mfile = File(fileName)
  mtime = mfile.lastModified()
  dtime = Date(mtime).toString()
  say 'File' fileName 'last modified at' dtime
  say
  if mfile.setLastModified(0) then do
    dtime = Date(mfile.lastModified()).toString()
    say 'File modification time altered...'
    say 'File' fileName 'now last modified at' dtime
    say
    say 'Resetting...'
    mfile.setLastModified(mtime)
    dtime = Date(mfile.lastModified()).toString()
    say 'File' fileName 'reset to last modified at' dtime
    end
  else do
    say 'Unable to modify time for file' fileName
    end
  return


;; print modification time
(println (date (file-info "input.txt" 6)))

;; set modification time to now (Unix)
(! "touch -m input.txt")


import os, strutils, times

if paramCount() == 0: quit(QuitSuccess)
let fileName = paramStr(1)

# Get and display last modification time.
var mtime = fileName.getLastModificationTime()
echo "File \"$1\" last modification time: $2".format(fileName, mtime.format("YYYY-MM-dd HH:mm:ss"))

# Change last modification time to current time.
fileName.setLastModificationTime(now().toTime())


use System.IO.File;

class Program {
  function : Main(args : String[]) ~ Nil {
    File->ModifiedTime("file_mod.obs")->ToString()->PrintLine();
  }
}


NSFileManager *fm = [NSFileManager defaultManager];

// Pre-OS X 10.5
NSLog(@"%@", [[fm fileAttributesAtPath:@"input.txt" traverseLink:YES] fileModificationDate]);
[fm changeFileAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate]
                  atPath:@"input.txt"];

// OS X 10.5+
NSLog(@"%@", [[fm attributesOfItemAtPath:@"input.txt" error:NULL] fileModificationDate]);
[fm setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate]
     ofItemAtPath:@"input.txt" error:NULL];


#load "unix.cma";;
open Unix;;
let mtime = (stat filename).st_mtime;; (* seconds since the epoch *)

utimes filename (stat filename).st_atime (time ());;
(* keep atime unchanged
   set mtime to current time *)


FILE-INFO:FILE-NAME = 'c:/temp'.
MESSAGE
   STRING( FILE-INFO:FILE-MOD-TIME, 'HH:MM:SS' )
VIEW-AS ALERT-BOX


declare
  [Path] = {Module.link ['x-oz://system/os/Path.ozf']}
  Modified = {Path.mtime "input.txt"} %% posix time
in
  {Show {OsTime.localtime Modified}} %% human readable record


my $mtime = (stat($file))[9]; # seconds since the epoch

# you should use the more legible version below:
use File::stat qw(stat);
my $mtime = stat($file)->mtime; # seconds since the epoch

utime(stat($file)->atime, time, $file);
# keep atime unchanged
# set mtime to current time


without js -- file i/o
-- (however get as per the JavaScript entry above might be doable if needed)
constant filename = "test.txt"
?get_file_date(filename)

include timedate.e
?format_timedate(get_file_date(filename))
bool res = set_file_date(filename)
?format_timedate(get_file_date(filename))


<?php
$filename = 'input.txt';

$mtime = filemtime($filename); // seconds since the epoch

touch($filename,
      time(), // set mtime to current time
      fileatime($filename)); // keep atime unchanged
?>


(let File "test.file"
   (and
      (info File)
      (prinl (stamp (cadr @) (cddr @))) ) # Print date and time in UTC
   (call 'touch File) )                   # Set modification time to "now"


;;; Print modification time (seconds since Epoch)
sysmodtime('file') =>


$modificationTime = (Get-ChildItem file.txt).LastWriteTime
Set-ItemProperty file.txt LastWriteTime (Get-Date)

$LastReadTime = (Get-ChildItem file.txt).LastAccessTime
Set-ItemProperty file.txt LastAccessTime(Get-Date)

$CreationTime = (Get-ChildItem file.txt).CreationTime
Set-ItemProperty file.txt CreationTime(Get-Date)


Debug FormatDate("%yyyy/%mm/%dd", GetFileDate("file.txt",#PB_Date_Modified))
  SetFileDate("file.txt",#PB_Date_Modified,Date(1987, 10, 23, 06, 43, 15))
Debug FormatDate("%yyyy/%mm/%dd - %hh:%ii:%ss", GetFileDate("file.txt",#PB_Date_Modified))


import os

#Get modification time:
modtime = os.path.getmtime('filename')

#Set the access and modification times:
os.utime('path', (actime, mtime))

#Set just the modification time:
os.utime('path', (os.path.getatime('path'), mtime))

#Set the access and modification times to the current time:
os.utime('path', None)


# Get the value
file.info(filename)$mtime

#To set the value, we need to rely on shell commands.  The following works under windows.
shell("copy /b /v filename +,,>nul")
# and on Unix (untested)
shell("touch -m filename")


#lang racket
(file-or-directory-modify-seconds "foo.rkt")


use NativeCall;

class utimbuf is repr('CStruct') {
    has int $.actime;
    has int $.modtime;

    submethod BUILD(:$atime, :$mtime) {
        $!actime = $atime;
        $!modtime = $mtime.to-posix[0].round;
    }
}

sub sysutime(Str, utimbuf --> int32) is native is symbol('utime') {*}

sub MAIN (Str $file) {
    my $mtime = $file.IO.modified orelse .die;

    my $ubuff = utimbuf.new(:atime(time),:mtime($mtime));

    sysutime($file, $ubuff);
}


name$ = DIR$("input.txt", 0)
PRINT "File date: "; FileRec.Date
PRINT "File time: "; FileRec.Time


Function getModDate(f As FolderItem) As Date
  Return f.ModificationDate
End Function


/*REXX program obtains and displays a  file's  time of modification.                    */
parse arg $ .                                    /*obtain required argument from the CL.*/
if $==''  then do;  say "***error*** no filename was specified.";   exit 13;   end
q=stream($, 'C', "QUERY TIMESTAMP")              /*get file's modification time info.   */
if q==''  then q="specified file doesn't exist." /*set an error indication message.     */
say 'For file: '  $                              /*display the file ID information.     */
say 'timestamp of last modification: ' q         /*display the modification time info.  */
                                                 /*stick a fork in it,  we're all done. */


load "stdlib.ring"
see GetFileInfo( "test.ring" )

func GetFileInfo cFile
     cOutput = systemcmd("dir /T:W " + cFile )
     aList = str2list(cOutput)
     cLine = aList[6]
     aInfo = split(cLine," ")
     return aInfo


#Get modification time:
modtime = File.mtime('filename')

#Set the access and modification times:
File.utime(actime, mtime, 'path')

#Set just the modification time:
File.utime(File.atime('path'), mtime, 'path')

#Set the access and modification times to the current time:
File.utime(nil, nil, 'path')


files #f, DefaultDir$ + "\*.*"                  ' all files in the default directory

print "hasanswer: ";#f HASANSWER()              ' does it exist
print "rowcount: ";#f ROWCOUNT()                ' number of files in the directory
print                                           '
#f DATEFORMAT("mm/dd/yy")                       ' set format of file date to template given
#f TIMEFORMAT("hh:mm:ss")                       ' set format of file time to template given

for i = 1 to #f rowcount()                      ' loop through the files
if #f hasanswer() then                          '  or loop with while #f hasanswer()
 print "nextfile info: ";#f nextfile$("    ")   ' set the delimiter for nextfile info
 print "name: ";name$                           ' file name
 print "size: ";#f SIZE()                       ' file size
 print "date: ";#f DATE$()                      ' file date
 print "time: ";#f TIME$()                      ' file time
 print "isdir: ";#f ISDIR()                     ' is it a directory or file

 name$ = #f NAME$()
 shell$("touch -t 201002032359.59 ";name$;""")  ' shell to os to set date

 print
end if
next


use std::fs;

fn main() -> std::io::Result<()> {
    let metadata = fs::metadata("foo.txt")?;

    if let Ok(time) = metadata.accessed() {
        println!("{:?}", time);
    } else {
        println!("Not supported on this platform");
    }
    Ok(())
}


import java.io.File
import java.util.Date

object FileModificationTime extends App {
  def test(file: File) {
    val (t, init) = (file.lastModified(),
      s"The following ${if (file.isDirectory()) "directory" else "file"} called ${file.getPath()}")

    println(init + (if (t == 0) " does not exist." else " was modified at " + new Date(t).toInstant()))
    println(init +
      (if (file.setLastModified(System.currentTimeMillis())) " was modified to current time." else " does not exist."))
    println(init +
      (if (file.setLastModified(t)) " was reset to previous time." else " does not exist."))
  }

  // main
  List(new File("output.txt"), new File("docs")).foreach(test)
}


$ include "seed7_05.s7i";
  include "osfiles.s7i";
  include "time.s7i";

const proc: main is func
  local
    var time: modificationTime is time.value;
  begin
    modificationTime := getMTime("data.txt");
    setMTime("data.txt", modificationTime);
  end func;


var file = File.new(__FILE__);
say file.stat.mtime;            # seconds since the epoch

# keep atime unchanged
# set mtime to current time
file.utime(file.stat.atime, Time.now);


slate[1]> (File newNamed: 'LICENSE') fileInfo modificationTimestamp.
1240349799


|a|
a := File name: 'input.txt'.
(a lastModifyTime) printNl.


val mtime = OS.FileSys.modTime filename; (* returns a Time.time data structure *)

(* unfortunately it seems like you have to set modification & access times together *)
OS.FileSys.setTime (filename, NONE); (* sets modification & access time to now *)
(* equivalent to: *)
OS.FileSys.setTime (filename, SOME (Time.now ()))


# Get the modification time:
set timestamp [file mtime $filename]

# Set the modification time to ‘now’:
file mtime $filename [clock seconds]


$$ MODE TUSCRIPT
file="rosetta.txt"
ERROR/STOP OPEN (file,READ,-std-)
modified=MODIFIED (file)
PRINT "file ",file," last modified: ",modified


decl java.util.Date d
decl file f

f.open "example.txt"
d.setTime (f.lastmodified)
out d endl console

f.setlastmodified 10


Dim file As New IO.FileInfo("test.txt")

'Creation Time
Dim createTime = file.CreationTime
file.CreationTime = createTime.AddHours(1)

'Write Time
Dim writeTime = file.LastWriteTime
file.LastWriteTime = writeTime.AddHours(1)

'Access Time
Dim accessTime = file.LastAccessTime
file.LastAccessTime = accessTime.AddHours(1)