Go language self-study series | golang standard library os module - File file read operation

Video source: Station B "Golang entry to project combat [2021 latest Go language tutorial, no nonsense, pure dry goods! Continuing to update...]"

While studying, organize the teacher's course content and test notes, and share them with everyone. Please move to the Zhihu website. Thank you for your support!

Attached a summary post: Go language self-study series | Summary - Zhihu (zhihu.com) icon-default.png?t=M276https://zhuanlan.zhihu.com/p/484035621


This ends the file read operation related to the File structure

package main

import (
    "fmt"
    "os"
)

// 打开关闭文件
func openCloseFile() {
    // 只能读
    f, _ := os.Open("a.txt")
    fmt.Printf("f.Name(): %v\n", f.Name())
    // 根据第二个参数 可以读写或者创建
    f2, _ := os.OpenFile("a1.txt", os.O_RDWR|os.O_CREATE, 0755)
    fmt.Printf("f2.Name(): %v\n", f2.Name())

    err := f.Close()
    fmt.Printf("err: %v\n", err)
    err2 := f2.Close()
    fmt.Printf("err2: %v\n", err2)
}

// 创建文件
func createFile() {
    // 等价于:OpenFile(name, O_RDWF|O_CREATE|O_TRUNK, 0666)
    f, _ := os.Create("a2.txt")
    fmt.Printf("f.Name(): %v\n", f.Name())
    // 第一个参数 目录默认:Temp 第二个参数 文件名前缀
    f2, _ := os.CreateTemp("", "temp")
    fmt.Printf("f2.Name(): %v\n", f2.Name())
}

// 读操作
func readOps() {
    // 循环读取
    /* f, _ := os.Open("a.txt")
    for {
        buf := make([]byte, 6)
        n, err := f.Read(buf)
        fmt.Printf("string(buf): %v\n", string(buf))
        fmt.Printf("n: %v\n", n)
        if err == io.EOF {
            break
        }
    }
    f.Close() */

    /* buf := make([]byte, 10)
    f2, _ := os.Open("a.txt")
    // 从5开始读10个字节
    n, _ := f2.ReadAt(buf, 5)
    fmt.Printf("n: %v\n", n)
    fmt.Printf("string(buf): %v\n", string(buf))
    f2.Close() */

    // 测试 a目录下有b和c目录
    /* f, _ := os.Open("a")
    de, _ := f.ReadDir(-1)
    for _, v := range de {
        fmt.Printf("v.IsDir(): %v\n", v.IsDir())
        fmt.Printf("v.Name(): %v\n", v.Name())
    } */

    // 定位
    f, _ := os.Open("a.txt")
    f.Seek(3, 0)
    buf := make([]byte, 10)
    n, _ := f.Read(buf)
    fmt.Printf("n: %v\n", n)
    fmt.Printf("string(buf): %v\n", string(buf))
    f.Close()
}

func main() {
    // openCloseFile()
    // createFile()
    readOps()
}

Guess you like

Origin blog.csdn.net/guolianggsta/article/details/123608444
Recommended