GolangNote

Golang笔记

golang 添加内容到文件末尾

Permalink

添加字符串到文件末尾

golang 添加内容到文件末尾

Go: 添加内容到文件末尾
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
	"fmt"
	"os"
)

func main() {
	// 用读写的方式打开文件
	file, err := os.OpenFile("input.txt", os.O_APPEND|os.O_WRONLY, 0600)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	if _, err = file.WriteString(" 这是添加的内容"); err != nil {
		panic(err)
	}

	fmt.Println("已成功添加")
}

golang http://golang.org/src/pkg/os/file.go 里定义的相关参数:

Go: const 文件打开方式
1
2
3
4
5
6
7
8
9
10
const (
	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
	O_WRONLY int = syscall.O_WRONLY // open the file write-only.
	O_RDWR   int = syscall.O_RDWR   // open the file read-write.
	O_APPEND int = syscall.O_APPEND // append data to the file when writing.
	O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
	O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist
	O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
	O_TRUNC  int = syscall.O_TRUNC  // if possible, truncate file when opened.
)

Related articles

Write a Comment to "golang 添加内容到文件末尾"

Submit Comment Login
Based on Golang + fastHTTP + youdb | go1.16 Processed in 1ms