1 % (c) 2009-2024 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(tools_files,
6 [write_lines_to_file/2,
7 write_to_file/2,
8 write_to_utf8_file/2, write_to_utf8_file_or_user_output/2,
9 put_codes/2,
10 read_file_codes/2]).
11
12
13 :- use_module(module_information).
14
15 :- module_info(group,infrastructure).
16 :- module_info(description,'A few utilities on files seperated out from tools.pl to avoid cyclic module dependencies.').
17
18 write_lines_to_file(FILE,Lines) :-
19 lines_to_code_list(Lines,CodeList),
20 write_to_file(FILE,CodeList).
21
22 lines_to_code_list([],[]).
23 lines_to_code_list([Line|Lines],CodeList) :-
24 (number(Line) -> number_codes(Line,L); atom_codes(Line,L)),
25 append(L,[10],L1),
26 append(L1,RL,CodeList),
27 lines_to_code_list(Lines,RL).
28
29 write_to_utf8_file(FILE,CodesList) :-
30 open(FILE,write,S,[encoding(utf8)]),
31 put_codes(CodesList,S),
32 close(S).
33
34 write_to_utf8_file_or_user_output(user_output,CodesList) :- !,
35 put_codes(CodesList,user_output).
36 write_to_utf8_file_or_user_output(FILE,CodesList) :- write_to_utf8_file(FILE,CodesList).
37
38 write_to_file(FILE,CodesList) :-
39 open(FILE,write,S),
40 put_codes(CodesList,S),
41 close(S).
42
43 put_codes([],_).
44 put_codes([H|T],Stream) :- put_code(Stream,H), put_codes(T,Stream).
45
46
47
48 read_file_codes(Filename,Codes) :-
49 open(Filename,read,S,[encoding(utf8)]),
50 call_cleanup(read_codes(S,Codes),
51 close(S)).
52 read_codes(S,Codes) :-
53 get_code(S,Code),
54 ( Code < 0 ->
55 Codes = []
56 ;
57 Codes = [Code|Rest],
58 read_codes(S,Rest)).