forked from Mercury-Language/mercury
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cat.m
94 lines (77 loc) · 2.48 KB
/
cat.m
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
89
90
91
92
93
94
%-----------------------------------------------------------------------------%
% vim: ft=mercury ts=4 sw=4 et
%-----------------------------------------------------------------------------%
%
% Simple implementation of the standard unix `cat' filter:
% copy input files (or stdin, if no input files) to stdout.
%
% This source file is hereby placed in the public domain. -fjh (the author).
%
%-----------------------------------------------------------------------------%
:- module cat.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
%-----------------------------------------------------------------------------%
%-----------------------------------------------------------------------------%
:- implementation.
:- import_module char.
:- import_module list.
:- import_module string.
%-----------------------------------------------------------------------------%
main(!IO) :-
io.command_line_arguments(Args, !IO),
(
Args = [],
cat(!IO)
;
Args = [_ | _],
cat_file_list(Args, !IO)
).
:- pred cat_file_list(list(string)::in, io::di, io::uo) is det.
cat_file_list([], !IO).
cat_file_list([File | Files], !IO) :-
cat_file(File, !IO),
cat_file_list(Files, !IO).
:- pred cat_file(string::in, io::di, io::uo) is det.
cat_file(File, !IO) :-
io.open_input(File, Result, !IO),
(
Result = ok(Stream),
cat_stream(Stream, !IO),
io.close_input(Stream, !IO)
;
Result = error(Error),
io.progname("cat", Progname, !IO),
io.error_message(Error, Message),
io.write_strings([
Progname, ": ",
"error opening file `", File, "' for input:\n\t",
Message, "\n"
], !IO)
).
:- pred cat_stream(io.input_stream::in, io::di, io::uo) is det.
cat_stream(Stream, !IO) :-
io.set_input_stream(Stream, _OldStream, !IO),
cat(!IO).
:- pred cat(io::di, io::uo) is det.
cat(!IO) :-
io.read_line_as_string(Result, !IO),
(
Result = ok(Line),
io.write_string(Line, !IO),
cat(!IO)
;
Result = eof
;
Result = error(Error),
io.error_message(Error, Message),
io.input_stream_name(StreamName, !IO),
io.progname("cat", ProgName, !IO),
io.write_strings([
ProgName, ": ",
"error reading input file `", StreamName, "': \n\t",
Message, "\n"
], !IO)
).
%-----------------------------------------------------------------------------%