Golang 对文件的增删改查操作

时间:2023-03-21
本文章向大家介绍Golang 对文件的增删改查操作,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"strings"
	"text/template"
)

type HostsEntry struct {
	IP   string
	Host string
}

func Add(filepath string, str []HostsEntry) error {
	// 定义模板
	hostsTmpl := `{{.IP}} {{.Host}}
`
	// 准备数据
	//hostsEntries := []HostsEntry{
	//	{IP: "127.0.0.1", Host: "localhost"},
	//	{IP: "192.168.1.100", Host: "host1.example.com"},
	//	{IP: "192.168.1.101", Host: "host2.example.com"},
	//}
	hostsEntries := str
	// 打开文件
	file, err := os.OpenFile(filepath, os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	defer file.Close()

	// 创建模板
	tmpl, err := template.New("host").Parse(hostsTmpl)
	if err != nil {
		return err
	}

	// 应用模板并追加到文件
	for _, entry := range hostsEntries {
		err = tmpl.Execute(file, entry)
		if err != nil {
			return err
		}
	}
	return nil
}

func Delete(filepath string, str string) error {
	file, err := os.OpenFile(filepath, os.O_RDWR, 0644)
	if err != nil {
		return err
	}
	defer file.Close()

	// 创建一个新的临时文件
	tmpFile, err := os.CreateTemp("", "tempfile")
	if err != nil {
		return err
	}
	defer tmpFile.Close()

	// 扫描文件并删除包含指定字符串的行
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		if !strings.Contains(line, str) {
			_, err := tmpFile.WriteString(line + "\n")
			if err != nil {
				return err
			}
		}
	}
	// 关闭文件并重命名临时文件
	file.Close()
	tmpFile.Close()
	err = os.Rename(tmpFile.Name(), filepath)
	if err != nil {
		return err
	}
	return nil
}

func Modify(filepath, oldstr, newstr string) error {
	// 打开文件
	file, err := os.OpenFile(filepath, os.O_RDWR, 0644)
	if err != nil {
		return err
	}
	defer file.Close()

	// 读取文件并存储在内存中
	scanner := bufio.NewScanner(file)
	var lines []string
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}

	// 修改所需的行
	for i, line := range lines {
		if strings.Contains(line, oldstr) {
			lines[i] = newstr
			break
		}
	}

	// 将修改后的数据写回文件中
	file.Truncate(0) // 清空文件内容
	file.Seek(0, 0)  // 将文件指针移到文件开头
	writer := bufio.NewWriter(file)
	for _, line := range lines {
		fmt.Fprintln(writer, line)
	}
	writer.Flush()
	return nil

}

func Get(filepath, str string) (bool, error) {
	// 打开文件
	file, err := os.OpenFile(filepath, os.O_RDONLY, 0644)
	if err != nil {
		return true, err
	}
	defer file.Close()

	// 扫描文件并删除包含指定字符串的行
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		if !strings.Contains(line, str) {
			return true, nil
		}
	}
	return false, nil

}

func Shellout(command string) (error, string, string) {
	const ShellToUse = `bash`
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	cmd := exec.Command(ShellToUse, "-c", command)
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Run()
	return err, stdout.String(), stderr.String()
}

func main() {
	hostsEntries := []HostsEntry{
		{IP: "127.0.0.1", Host: "localhost"},
		{IP: "192.168.1.100", Host: "host1.example.com"},
		{IP: "192.168.1.101", Host: "host2.example.com"},
	}
	Add("drop.conf", hostsEntries)
	result, err := Get("drop.conf", "192.168.1.100")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(result)
	Modify("drop.conf", "host1.example.com", "1.1.1.1 host111.example.com")
	Delete("drop.conf", "host111.example.com")
	err, stdout, stderr := Shellout("ls -al")
	if err != nil {
		fmt.Println("执行错误")
	}
	fmt.Println(stdout, stderr)
}

原文地址:https://www.cnblogs.com/dqforgive-sudo/p/17238522.html