Some simple code, created as part of
my revision of Ch. 2 of Maxima by Example,
illustrates simple Maxima programming in
the context of string manipulation.
Here we use file_convert(source-file, new-file, new-type)
to convert a windows eol file [cr][lf] to unix eol file [lf].
-------------------------
(%i1) load(eol_chars);
(%o1) "c:/work2/eol_chars.mac"
(%i2) printfile("text1w.txt")$
is this line one? Yes, this is line one.
This might be line two.
Here is line three.
I insist that this be line four.
This is line five, isn't it?
(%i3) eol_chars("text1w.txt");
(%o3) [13,10]
(%i4) file_length("text1w.txt");
(%o4) 152
(%i5) file_convert("text1w.txt","text2u.txt",unix);
(%o5) true
(%i6) printfile("text2u.txt")$
is this line one? Yes, this is line one.
This might be line two.
Here is line three.
I insist that this be line four.
This is line five, isn't it?
(%i7) eol_chars("text2u.txt");
(%o7) [10]
(%i8) file_length("text2u.txt");
(%o8) 147
-----------------------------------
code:
read_text(%filename) :=
block ([%s,%r:[],%l ],
if not stringp (%filename)
then ( disp (" file name must be a Maxima string "),
return (false)),
if not file_search (%filename) then
(disp (" file not found "),return (false)),
%s : openr (%filename),
while (%l : readline(%s)) # false do
%r : cons (%l,%r),
close(%s),
reverse (%r))$
file_length (%fname) :=
block ([%s,%fl ],
%s : openr (%fname),
/* number of chars in file */
%fl : flength (%s),
close (%s),
%fl)$
eol_chars(%fname) :=
block([%s,%lch,eolL :[],%nch,%Nf : 0 ],
if not file_search (%fname)
then (disp(" file not found "),return(false)),
%s : openr (%fname),
do
( %lch : ?read\-char (%s,false),
if %lch = false then return(),
%nch : cint (cunlisp (%lch)),
if not lfreeof ([10,13],%nch) then
(%Nf : %Nf + 1,
eolL : cons (%nch,eolL),
if %Nf = 2 then return ())
else
if %Nf = 1 then return()),
close(%s),
reverse (eolL))$
file_convert(%oldfname,%newfname,%newtype) :=
block ([%ntL,%otL,%snew,%eolL,%linesL,%l1 ],
if %newtype = windows then %ntL : [13,10]
else if %newtype = unix then %ntL : [10]
else if %newtype = mac then %ntL : [13]
else
(disp (" valid types are windows, unix and mac "),
return (false)),
%otL : eol_chars (%oldfname),
if %otL = %ntL then
( print ("check of first line of source file shows eol chars are
already ",%newtype),
return (false)),
%snew : openw (%newfname),
/* convert decimal form to strings */
%eolL : map ('ascii, %ntL),
/* create list of strings containing contents
(including blank lines) of old file using
read_text (which uses readline, based on use
of Lisp read-line ) */
%snew : openw (%newfname),
%linesL : read_text (%oldfname),
if (not %linesL) or (length (%linesL) = 0)
then ( close(%snew), return(false)),
for %l1 in %linesL do
( flatten (cons (%l1, %eolL)),
apply ('sconcat, %%),
printf (%snew,"~a",%%)),
close (%snew))$
--------------------------------------
Ted Woollett