I need to make a program in fsharp which replaces all occurrences of a string "needle" in an input text file with another string "replace". A nice solution to this problem has already been posted here:
F# - fileReplace, overwriting words in txt, but when running it overwrites exisiting content in txt
Unfortunately, my program has to explicitly use the functions System.IO.File.OpenText, ReadLine and WriteLine which the aforementioned solution does not.
I cannot see how this can be done in an effective and non-convoluted way. Problem is that if you use System.IO.File.OpenText to open the input file, then you cannot both read and write to the file. But we need to write in order to replace the aforementioned occurrences of the needle argument. So what to do then? do you need to make another temporary file, open it as write-only and then perform the WriteLine on it with input equal to system.IO.FILe.OpenText.readLine? This seems too complicated.
I will add the specific assignment below if anyone needs it:
Make a program in F#
fileReplace : string -> needle : string -> replace: string -> unitwhich replaces all occurrences of the needle argument with the replace argument in the file with name filename. The solution must as a minimum use the functions System.IO.File.OpenText, ReadLine and WriteLine to access the files.
A short test must be included and a short description of the solution with arguments for larger design choices taken to reach the given solution
To help you a bit without giving out the entire answer, the following example shows a bit how to use the functions mentioned in the assignment to work with files.
It implements a simple code snippet that reads data from one text file line by line and writes the data (without replacing anything) to another file:
open System.IO
let fileIn = File.OpenText("C:\\Temp\\test-in.txt")
let fileOut = File.CreateText("C:\\Temp\\test-out.txt")
let mutable line = fileIn.ReadLine()
while line <> null do
fileOut.WriteLine(line)
line <- fileIn.ReadLine()
fileIn.Close()
fileOut.Close()
The tricky thing here is that ReadLine returns null at the end of the file. Dealing with this in a nice functional way is not very nice, so I just used mutable variable and while loop, but you could do the same using recursion or list comprehensions.
This reads data from one file and writes it line-by-line into another file. This avoids the need to read everything into memory, but it means you need two files, because you cannot (using those functions) overwrite the file while you're reading it.
To solve your problem, you could either create a temp file and then replace the original one with the new file, or you can read all data into memory before doing the replacing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With