The Go language removes empty lines from a file

  • 2020-05-24 05:41:42
  • OfStack

This article demonstrates an example of how the Go language can clear empty lines from a file. Share with you for your reference. The specific implementation method is as follows:

The Go language is used to read the source file, remove the blank lines, and write to the target file

/**
 * Created with IntelliJ IDEA.
 * User: hyper-carrot
 * Date: 12-8-31
 * Time: In the afternoon 4:04
 * To change this template use File | Settings | File Templates.
 */
package main
import (
 "os"
 "bufio"
 "fmt"
)
func DeleteBlankFile(srcFilePah string, destFilePath string) error {
 srcFile, err := os.OpenFile(srcFilePah, os.O_RDONLY, 0666)
 defer srcFile.Close()
 if err != nil {
  return err
 }
 srcReader := bufio.NewReader(srcFile)
 destFile, err := os.OpenFile(destFilePath, os.O_WRONLY|os.O_CREATE, 0666)
 defer destFile.Close()
 if err != nil {
  return err
 }
 var destContent string
 for {
  str, _ := srcReader.ReadString('\n')
  if err != nil {
   if err == io.EOF {
    fmt.Print("The file end is touched.")
    break
   } else {
    return err
   }
  }
  if 0 == len(str) || str == "\r\n" {
   continue
  }
  fmt.Print(str)
  destFile.WriteString(str)
 }
 return nil
}
func main() {
 DeleteBlankFile("e:\\src.txt", "e:\\dest.txt")
}

I hope this article has been helpful to your programming of Go language.


Related articles: