Go语言清除文件中空行的方法
程序员文章站
2022-05-14 20:49:45
本文实例讲述了go语言清除文件中空行的方法。分享给大家供大家参考。具体实现方法如下:
这里使用go语言读取源文件,去掉空行,并写到目标文件
复制代码 代码如下:/**...
本文实例讲述了go语言清除文件中空行的方法。分享给大家供大家参考。具体实现方法如下:
这里使用go语言读取源文件,去掉空行,并写到目标文件
复制代码 代码如下:
/**
* created with intellij idea.
* user: hyper-carrot
* date: 12-8-31
* time: 下午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")
}
* created with intellij idea.
* user: hyper-carrot
* date: 12-8-31
* time: 下午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")
}
希望本文所述对大家的go语言程序设计有所帮助。