F# - fileReplace, overwriting words in txt, but when running it overwrites exisiting content in txt

筅森魡賤 提交于 2019-12-11 07:33:32

问题


    open System
//helpfunction
let fileReplace filename needle replace =
  let replaceIn (reader:System.IO.StreamReader) needle (replace: String) =
    while not(reader.EndOfStream) do
      let mutable allText = reader.ReadToEnd()
      allText <- allText.Replace(needle, replace)
    reader.Close()

  //start
  let reader = System.IO.File.OpenText filename
  let newText = replaceIn reader needle replace
  let writer = System.IO.File.CreateText filename
  writer.Write newText ; writer.Close()

// testing
let filename = @".\abc.txt"
let needle = "med"
let replace = "MED"
fileReplace filename needle replace

I've experimented a bunch moving reader.Close() around, but with no results yet. I know that if I insert printfn "%A" allText under reader.Close(), it prints the correct result, so I suspect its when I call writer that it goes wrong. I need the code to replace med, with MED in abc.txt. but instead it leaves an empty abc.txt


回答1:


The replaceIn function that you've written doesn't do anything. Let's separate this out:

let replaceIn (reader:System.IO.StreamReader) needle (replace: string) =
    while not(reader.EndOfStream) do
        let mutable allText = reader.ReadToEnd()
        allText <- allText.Replace(needle, replace)
    reader.Close()

First, look at the type of this function:

val replaceIn :  reader:System.IO.StreamReader -> needle:string -> replace:string -> unit

The first thing to note is that this function returns unit, that means newText always has a value of (), regardless of file content. That means you are always writing nothing to your file.

Furthermore, your loop is superfluous. You are reading to the end of the stream yet looping until the end of the stream - this loop is unnecessary. There is also no way to observe the results of the loop anyway because the mutable variable you are creating to store the result in is inside the loop.


So, let's look at an alternative:

let fileReplace filename (needle : string) (replace : string) =
    let allText = System.IO.File.ReadAllText filename
    let newText = allText.Replace(needle, replace)
    System.IO.File.WriteAllText(filename, newText)

As you can see, you don't even need to create the readers, you can just the helper functions in System.IO.File.



来源:https://stackoverflow.com/questions/40380851/f-filereplace-overwriting-words-in-txt-but-when-running-it-overwrites-exisi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!