# Writing a function to mimic Characters

I am working my way through Programming Paradigms via Mathematica (A First Course) and have answered the following question in lesson 25:

Write a function of one argument "s", a String, which writes the string "s" to some file and then reads the string that file back in as a list of single characters. This operation thus mimics Characters[]. Pay attention to the methods Mathematica has for reading in data from a file.

In   Characters["the cow jumped over the moon"]

Out   {t, h, e,  , c, o, w,  , j, u, m, p, e, d,  , o, v, e, r,  , t, h, e,  , m, o, o, n}


My function is as follows:

Clear[myCharacters]
myCharacters[s_String] :=
Module[{myStream},
myStream = OpenWrite["file2"];
Write[myStream, s];
Close[myStream];
];
myCharacters["the cow jumped over the moon"]


which produces an output that includes the leading and trailing quotation marks:

{",t, h, e,  , c, o, w,  , j, u, m, p, e, d,  , o, v, e, r,  , t, h, e,  , m, o, o, n,"}


So thinking back to my previous question, where I had a couple of significant mistakes, I am wondering if there is something that I am missing or is my answer basically correct? Also I would appreciate being shown how I could improve my function even if it does give correct output.

-

The one-line fix is to use WriteString in place of Write. This writes the literal string rather than the corresponding Mathematica expression, which is delimited by quotation marks.

The same thing could be accomplished by using BinaryWrite because as the documentation states:

BinaryWrite[channel,"string"] writes the raw sequence of characters in a string.

To use it however you must open your stream appropriately:

OpenWrite["file2", BinaryFormat -> True]


If you are not set on using streams this can be done more simply with Export as unlike Write or Put this function can conveniently write raw strings (again, rather than Mathematica String expression syntax).

myCharacters[s_String] := ReadList[Export["\$file", s, "String"], Character]


Note that since Export returns the name of the file I used it inside ReadList directly.

-
Mr. Wizard, thank you for your help. –  Clif Aug 16 '13 at 1:15