读取目录下所有内容,并取前30页和后30页

package main

import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
)

/**

  • @Description $
  • @Author hll
  • @Date 2022/5/17 15:11
    **/
    func main() {
    readSource()
    getTotalLine()
    SpliteFile()
    }

var sourceDir = "E:\cpp_work\hll"
var dirfile = "E:\cpp_work\ps.txt"

//每页行数
var line_num_page int = 45

//当前读取的行数
var current_line int = 0

var total_line = 0

func readSource() {

_, err := os.Lstat(dirfile)
if err == nil {
    os.Remove(dirfile)
}

filepath.Walk(sourceDir, func(path string, info os.FileInfo, err error) error {
    if !info.IsDir() {
        cent, err := ioutil.ReadFile(path)

        fl, err := os.OpenFile(dirfile, os.O_APPEND|os.O_CREATE, 0644)
        if err != nil {
            panic(err)
        }
        defer fl.Close()
        fl.Write(cent)

    }
    return nil
})

}

func getTotalLine() {
f, err := os.Open(dirfile)
if err != nil {
panic(err)
}
defer f.Close()
r := bufio.NewReader(f)
for {
_, _, err := r.ReadLine()
if err == io.EOF {
break
}
total_line++
}
}
func SpliteFile() {
fmt.Println("总行数:", total_line)
f, err := os.Open(dirfile)
if err != nil {
panic(err)
}
defer f.Close()
var cent []string
r := bufio.NewReader(f)
for {
line, _, err := r.ReadLine()
if err == io.EOF {
break
}
current_line++
if current_line < line_num_page30 || current_line+line_num_page30 > total_line {
cent = append(cent, string(line))
}
}
newdirfile := "E:\cpp_work\new_ps.txt"
os.Remove(newdirfile)
fl, err := os.OpenFile(newdirfile, os.O_APPEND|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
panic(err)
}
defer fl.Close()
for _, s := range cent {
fl.WriteString(s + "\r\n")
}

}

你可能感兴趣的:(读取目录下所有内容,并取前30页和后30页)