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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
require 'zlib'
class ReadFile
def initialize fn, encoding='utf-8'
if fn.split('.').last == 'gz'
@f = Zlib::GzipReader.new(File.new(fn, 'rb'), :external_encoding=>encoding)
elsif fn == '-'
@f = STDIN
STDIN.set_encoding encoding
else
@f = File.new fn, 'r'
@f.set_encoding encoding
end
end
def gets
@f.gets { |line| yield line }
end
def readlines
@f.readlines
end
def self.readlines fn, encoding='utf-8'
f = ReadFile.new fn, encoding
r = f.readlines
f.close
return r
end
def readlines_strip
self.readlines.map{ |i| i.strip }
end
def self.readlines_strip fn, encoding='utf-8'
f = ReadFile.new fn, encoding
r = f.readlines_strip
f.close
return r
end
def read
@f.read
end
def self.read fn, encoding='utf-8'
f = ReadFile.new fn, encoding
r = f.read
f.close
return r
end
def close
@f.close if @f!=STDIN
end
end
class WriteFile
def initialize fn, encoding='utf-8'
if fn.split('.').last == 'gz'
@f = Zlib::GzipWriter.new(File.new(fn, 'wb+'), :external_encoding=>encoding)
elsif fn == '-'
@f = STDOUT
STDOUT.set_encoding encoding
else
@f = File.new fn, 'w+'
@f.set_encoding encoding
end
end
def write s
@f.write s
end
def self.write s, fn, encoding='utf-8'
f = WriteFile.new fn, encoding
f.write s
f.close
end
def close
@f.close if @f!=STDIN
end
end
|