Search code examples
filehaskellio

Why can't I write to a file?


I am trying to create a csv file for testing purposes and when I try to write it, it continues to fluctuate either at 0kb or 1kb and only 1 record is written. It continues to fluctuate like this for a while until I get

openfile: permission denied

module Generator where 

    path="d:\\data.csv"
    cnt=1000000
    main::IO()
    main=do
        let payload=makeString
        writeToFile path cnt payload


    makeString::String
    makeString="0741142339,\r\n"

    writeToFile::String->Int->String->IO()
    writeToFile _ 0 _ =return ()
    writeToFile path cnt payload=writeFile path payload >> writeToFile path (cnt-1)  payload

If I try to write to a location on C:// I get not allowed permission.


Solution

  • Each call to writeFile overwrites the existing file with the next record.

    What you want to do is either

    • Open the file (openFile), write each line to the file handle (hPutStrLn), close the file at the end (hClose).
    • Generate a giant string representing the entire file contents, and writeFile that at the end.