Go语言中的IO

获取命令行参数

  • os.Args是一个string的切片,用来存储所有的命令行参数
  • flag包的使用,用来解析命令行参数:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    // 命令行参数
    func test() {
    var b bool
    var path string
    var port int
    // 预处理配置
    flag.BoolVar(&b, "b", false, "print on newline")
    flag.StringVar(&path, "c", "/conf.config", "Specify the configuration file. The default is /conf.config .")
    flag.IntVar(&port, "p", 8080, "Specify the port, the default is 8080")
    // 解析命令行标志
    flag.Parse()
    fmt.Printf("bool is %v\n", b)
    fmt.Printf("path is %s\n", path)
    fmt.Printf("port is %d\n", port)
    }

    func main() {
    test()
    }
    --------------------
    ./main -c /use/local/conf.config -p 8081 -b true

    bool is true
    path is /use/local/conf.config
    port is 8081

终端读写

  • os.Stdin:标准输入
  • os.Stdout:标准输出
  • os.Stderr:标准错误输出

终端读写示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
func main() {
fmt.Println("我能把字符串输出到控制台")
fmt.Fprintln(os.Stdout, "我也能把字符串输出到控制台")
var (
name string
age int
score float32
)

// 把字符串格式化到指定变量
fmt.Sscanf("张三,18,98.5", "%s,%d,%f", &name, &age, &score)
fmt.Println(name, age, score)
}

带缓冲区的读写示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func main() {
// 带缓冲区的读
var inputReader *bufio.Reader
inputReader = bufio.NewReader(os.Stdin)
fmt.Println("please enter some input:")
input, err := inputReader.ReadString('\n')
if err != nil {
fmt.Printf("input err:\n", err)
}
fmt.Printf("the input was %s\n", input)
}
------------------------
please enter some input:
123
the input was 123

文件读写:

  • os.File封装所有文件相关操作,os.Stdin,os.Stdout, os.Stderr都是*os.File
  • 打开一个文件进行读操作: os.Open(name string) (*File, error)
  • 关闭一个文件:File.Close()
  • 打开一个文件进行写操作:os.OpenFile(“output.dat”, os.O_WRONLY|os.O_CREATE, 0666)

第二个参数:文件打开模式
os.O_WRONLY:只写、os.O_CREATE:创建文件、os.O_RDONLY:只读、os.O_RDWR:读写、os.O_TRUNC:清空

第三个参数:权限控制:r ——> 004、w——> 002、x——> 001

文件读写操作示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 带缓冲区的读
func buffRead(rd io.Reader) {
var bufferReader *bufio.Reader
bufferReader = bufio.NewReader(rd)
str, err := bufferReader.ReadString('\n')
if err != nil {
fmt.Printf("input err:%s\n", err)
return
}
fmt.Printf("the input was %s\n", str)
}

// 从文件获取输入
func test2() {
file, err := os.Open("/1.txt")
if err != nil {
fmt.Printf("open file err:%s\n", err)
return
}
defer file.Close()
buffRead(file)
}

func main() {
test2()
}
-------------------------
the input was 1234567890

从文件中读取字符串,统计英文、数字、空格以及其他字符的数量:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
type charCount struct {
c int
n int
spance int
other int
}

func test() {
file, err := os.Open("/1.txt")
if err != nil {
fmt.Printf("open file err:%s\n", err)
return
}
defer file.Close()
var count charCount
var inputReader *bufio.Reader
inputReader = bufio.NewReader(file)
for {
str, err1 := inputReader.ReadString('\n')
if err1 == io.EOF {
fmt.Printf("read to the end of file\n")
break
}
if err != nil {
fmt.Printf("read file err:%s", err)
break
}

ru := []rune(str)
for _, v := range ru {
switch {
case v >= 'a' && v <= 'z':
fallthrough
case v >= 'A' && v <= 'Z':
count.c += 1
case v == ' ':
count.spance += 1
case v >= '0' && v <= '9':
count.n += 1
default:
count.other += 1
}
}
}
fmt.Printf("char num :%d \nspance num :%d\nnumber num:%d\nother num :%d\n", count.c, count.spance, count.n, count.other)
}

func main() {
test()

}
-------------------------
read to the end of file
char num :547
spance num :115
number num:11
other num :330

使用ioutil读取整个文件,并写到指定文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func test() {
inputFile := "/inputfile.txt"
outputFile := "/outputfile.txt"
// 一次读完整个文件
f, err := ioutil.ReadFile(inputFile)
if err != nil {
fmt.Printf("read file err:%s\n", err)
}

str := string(f)
fmt.Printf("file content:%s\n", str)
// 这里第三个参数设置输出文件的权限
err1 := ioutil.WriteFile(outputFile, f, 0x777)
if err1 != nil {
fmt.Printf("write file err:%s\n", err1)
}

}

func main() {
test()
}

读取压缩文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 读取解压文件示例:

func test() {
// 1.打开文件
fName := "go_dev/day7/example5/main/1.gz"
fi, err := os.Open(fName)
var r *bufio.Reader
if err != nil {
fmt.Printf("open file err:%s\n", err)
return
}
defer fi.Close()
// 2.gzip读取打开的文件句柄
grfi, err := gzip.NewReader(fi)
if err != nil {
fmt.Printf("open gzip failed err:%v\n", err)
return
}
// 3.用bufio.Reader接收gzip读取出的数据
r = bufio.NewReader(grfi)
for {
line, err := r.ReadString('\n')
if err != nil {
fmt.Println("Done reading file")
return
}
fmt.Println(line)
}
}

func main() {
test()
}

拷贝文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 拷贝文件
func copyFile(dstName, srcName string) (written int64, err error) {
// 打开源文件
srcFile, err := os.Open(srcName)
if err != nil {
fmt.Printf("open src file err:%s\n", err)
return
}
defer srcFile.Close()
// 打开或创建目标文件
dstFile, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Printf("open dst file err:%s\n", err)
return
}
defer dstFile.Close()

return io.Copy(dstFile, srcFile)
}

func main() {
num, _ := copyFile("/2.txt", "/1.txt")
fmt.Println(num)
}