[Haskell] [Haskell - I/O] Problem with 'readFile'

L. J. djsenda at gmail.com
Sun Aug 27 04:43:24 EDT 2006

On 8/27/06, L. J. <djsenda at gmail.com> wrote:
> On 8/27/06, John Hughes <rjmh at cs.chalmers.se> wrote:
> >
> >
> > > Hi, I use the operation 'readFile' for obtain information locates on
> > > a file. When I try to write another information on the same file, I
> > > obtain this error message: "openFile: permision denied". I found this:
> > > "The readFile operation holds a semi-closed handle on the file until
> > > the entire contents of the file have been consumed. It follows that an
> > > attempt to write to a file (using writeFile, for example) that was
> > > earlier opened by readFile will usually result in failure with
> > > isAlreadyInUseError." in this web
> > > http://www.haskell.org/onlinereport/io.html.
> > >
> > > How can I break that semi-closed handle for to write in the
> > > preaviously readed file? Thank you.
> >
> > readFile returns an *unevaluated* list of characters from the file--as your
> > program needs those characters, so they will be read from the file. Once
> > they have all been read, then the file is closed.  So to ensure that the
> > file is closed, you just have to make sure your program reads all the
> > characters. One way is to count them. So here's a function that reads a
> > file, then rewrites it with "hello" added at the beginning:
> >
> > addHello f = do
> >   s <- readFile f
> >   length s `seq` writeFile f ("hello"++s)
> >
> > length s counts the characters in the file (forcing it all to be read), and
> > the `seq` is like a semicolon in C: it forces length s to be computed before
> > the writeFile is performed.
> >
> > John
>  Thanks you for your code. I try with it and it works well, but I can
> not use it in my aplication because I read the file in one function, I
> compute the results with the readed information and, finally, I wrote
> this results in another function (in this moment I do not have the
> readed string, I have my structured data). How can I use this `seq`
> with different functions?

 I solve the problem, but my method could not be the better
(methodologically speaking). I insert this code inmediately after read
the file (with readFile):

  length mates_str `seq` return ()

 Is it so bad this code? I think it works so well.

More information about the Haskell mailing list