【原创】go语言学习(十五)IO操作2

目录

  • 文件打开和读写
  • 读取压缩文件
  • bufio原理和cat命令实现
  • defer详解

文件打开和读写

1、 文件是存储在外部介质上的数据集合。

A. 文件分类:文本文件和二进制文件

B. 文件存取方式:随机存取和顺序存放

2、文件打开

package main
import (
    "bufio"
    "fmt"
    "io"
    "os"
)
func main() {
    //只读的方式打开
    inputFile, err := os.Open("input.dat")
    if err != nil {
        fmt.Printf("open file err:%v\n", err)
        return
    }
    defer inputFile.Close()
}

  

3、文件读取, file.Read和file.ReadAt。读到文件末尾返回:io.EOF

package main
import (
    "bufio"
    "fmt"
    "io"
    "os"
)
func main() {
    //只读的方式打开
    inputFile, err := os.Open("input.dat")
    if err != nil {
        fmt.Printf("open file err:%v\n", err)
        return
    }
    var buf[128]byte
    inputFile.Read(buf[:])
    defer inputFile.Close()
}

  

4、 bufio原理

 

 5、bufio读取文件

package main
import (
    "bufio"
    "fmt"
    "io"
    "os"
)
func main() {
    inputFile, err := os.Open("input.dat")
    if err != nil {
        fmt.Printf("open file err:%v\n", err)
        return
    }
    defer inputFile.Close()
    inputReader := bufio.NewReader(inputFile)
    for {
        inputString, readerError := inputReader.ReadString('\n')
        if readerError == io.EOF {
            return
        }
        fmt.Printf("The input was: %s", inputString)
    }
}

  

6、读取整个文件示例

package main
import (
    "fmt"
    "io/ioutil"
    "os"
)
func main() {
    inputFile := "products.txt"
    outputFile := "products_copy.txt"
    buf, err := ioutil.ReadFile(inputFile)
    if err != nil {
        fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
        return
    }
    fmt.Printf("%s\n", string(buf))
}

  

读取压缩文件

1、读取压缩文件

package main
import (
    "bufio"
    "compress/gzip"
    "fmt"
    "os"
)
func main() {
    fName := "MyFile.gz"
    var r *bufio.Reader
    fi, err := os.Open(fName)
    if err != nil {
        fmt.Fprintf(os.Stderr, "%v, Can’t open %s: error: %s\n", os.Args[0], fName, err)
        os.Exit(1)
    }
    fz, err := gzip.NewReader(fi)
    if err != nil {
        fmt.Fprintf(os.Stderr, "open gzip failed, err: %v\n", err)
        return
    }
    r = bufio.NewReader(fz)
    for {
        line, err := r.ReadString('\n')
        if err != nil {
            fmt.Println("Done reading file")
            os.Exit(0)
        }
        fmt.Println(line)
    }
}

  

 

bufio原理和cat命令实现

1、文件写入

文件读写
os.OpenFile(“output.dat”, os.O_WRONLY|os.O_CREATE, 0666)
1. os.O_WRONLY:只写
第二个参数:文件打开模式

r ——> 004
w——> 002
x——> 001
第三个参数:权限控制:
2. os.O_CREATE:创建文件
3. os.O_RDONLY:只读
4. os.O_RDWR:读写
5. os.O_TRUNC :清空
6. os. O_APPEND:追加

2、文件写入示例

file.Write()
file.WriteAt()
file.WriteString()

package main
import (
    "bufio"
    "fmt"
    "os"
)
func main() {
    outputFile, outputError := os.OpenFile("output.dat",
    os.O_WRONLY|os.O_CREATE, 0666)
    if outputError != nil {
        fmt.Printf("An error occurred with file creation\n")
        return
    }
    str := “hello world”
    outputFile.Write([]byte(str))
    defer outputFile.Close()
}

  

3、 文件写入示例

package main
import (
    "bufio"
    "fmt"
    "os"
)
func main() {
    outputFile, outputError := os.OpenFile("output.dat",
    os.O_WRONLY|os.O_CREATE, 0666)
    if outputError != nil {
        fmt.Printf("An error occurred with file creation\n")
        return
    }
    defer outputFile.Close()
    outputWriter := bufio.NewWriter(outputFile)
    outputString := "hello world!\n"
    for i := 0; i < 10; i++ {
        outputWriter.WriteString(outputString)
    }
    outputWriter.Flush()
}

  

4、写入整个文件示例

package main
import (
    "fmt"
    "io/ioutil"
    "os"
)
func main() {
    inputFile := "products.txt"
    outputFile := "products_copy.txt"
    buf, err := ioutil.ReadFile(inputFile)
    if err != nil {
        fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
        return
    }
    fmt.Printf("%s\n", string(buf))
    err = ioutil.WriteFile(outputFile, buf, 0x644)
    if err != nil {
        panic(err.Error())
    }
}

  

5、拷贝文件

package main
import (
    "fmt"
    "io"
    "os"
)
func main() {
    CopyFile("target.txt", "source.txt")
    fmt.Println("Copy done!")
}
func CopyFile(dstName, srcName string) (written int64, err error) {
    src, err := os.Open(srcName)
    if err != nil {
        return
    }
    defer src.Close()
    dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
    if err != nil {
        return
    }
    defer dst.Close()
    return io.Copy(dst, src)
}

  

6、cat命令实现

package main
import (
    "bufio"
    "flag"
    "fmt"
    "io"
    "os"
)
func cat(r *bufio.Reader) {
    for {
        buf, err := r.ReadBytes('\n')
        if err == io.EOF {
            break
        }
        fmt.Fprintf(os.Stdout, "%s", buf)
        return
    }
}
func main() {
    flag.Parse()
    if flag.NArg() == 0 {
        cat(bufio.NewReader(os.Stdin))
    }
    for i := 0; i < flag.NArg(); i++ {
        f, err := os.Open(flag.Arg(i))
        if err != nil {
            fmt.Fprintf(os.Stderr, "%s:error reading from %s: %s\n",
            os.Args[0], flag.Arg(i), err.Error())
            continue
        }
        cat(bufio.NewReader(f))
    }
}

  

defer详解

1、defer原理分析

 

2、defer案例

package main
import (
    "fmt"
)
func funcA() int {
    x := 5
    defer func() {
        x += 1
    }()
    return x
}
func main() {
    fmt.Println(funcA())
}

  

3、defer案列2

package main
import "fmt"
func funcB() (x int) {
    defer func() {
        x += 1
    }()
    return 5
}
func main() {
    fmt.Println(funcB())
}

  

4、defer案例3

package main
import "fmt"
func funcC() (y int) {
    x := 5
    defer func() {
        x += 1
    }()
    return x
}
func main() {
    fmt.Println(funcC())
}

  

5、defer案例4

package main
import "fmt"
func funcD() (x int) {
    defer func(x int) {
        x += 1
    }(x)
    return 5
}
func main() {
    fmt.Println(funcD())
}

  

 

posted @ 2019-11-07 18:43  shuyang  阅读(308)  评论(0编辑  收藏  举报