-
Notifications
You must be signed in to change notification settings - Fork 0
/
csvcount
executable file
·49 lines (40 loc) · 1.19 KB
/
csvcount
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env php
<?php
class CSVCount {
const DEFAULT_LPAD = 1;
public static function main($argc, $argv) {
if($argc === 1 || $argv[1] === '-')
self::stdin();
elseif($argc === 2)
self::oneArg($argv[1]);
elseif($argc > 2)
self::manyArgs(array_slice($argv, 1));
}
public static function stdin() {
echo self::countRecords(STDIN) . "\n";
}
public static function oneArg($arg, $lpad=0) {
$count = self::countRecords(fopen($arg, 'r'));
printf("%{$lpad}s %s\n", $count, $arg);
return $count;
}
public static function countRecords($fp) {
for($count = 0; fgetcsv($fp); $count++);
return $count;
}
public static function manyArgs($args) {
$lpad = self::compute_lpad($args);
for($i = $totalRecords = 0, $argc = count($args);
$i < $argc;
$totalRecords += self::oneArg($args[$i], $lpad), $i++);
printf("%{$lpad}s total\n", $totalRecords);
}
public static function compute_lpad($args) {
for($i = $totalSize = 0, $argc = count($args);
$i < $argc;
$totalSize += filesize($args[$i]), $i++);
for($lpad = 1; $totalSize >= 10; $totalSize /= 10, $lpad++);
return $lpad > self::DEFAULT_LPAD ? $lpad : self::DEFAULT_LPAD;
}
}
CSVCount::main(count($argv), $argv);