zoukankan      html  css  js  c++  java
  • go打开文件

    go打开文件模式

    O_RDONLY  // open the file read-only.
    O_WRONLY  // open the file write-only.
    O_RDWR    // open the file read-write.
    // The remaining values may be or'ed in to control behavior.
    O_APPEND  // append data to the file when writing.
    O_CREATE  // create a new file if none exists.
    O_EXCL    // used with O_CREATE, file must not exist.
    O_SYNC    // open for synchronous I/O.
    O_TRUNC   // truncate regular writable file when opened.
    

    1.读全部

    import (
        "errors"
    	"fmt"
    	"io/ioutil"
        )
    f,err:=ioutil.ReadFile("./log.text")   // ReadFile 用的 OpenFile(name, O_RDONLY, 0)
        									// filename 不存在就就报错
    	if err!=nil{
    
    		fmt.Println("出错啦")
    	}
    	err1 := errors.New("错误")
    	fmt.Println("出错啦",err1)
        fmt.Println(string(f))
    

    2.每次读多少字节

    f,err:=os.Open("./log.text")  // OpenFile(name, O_RDONLY, 0) 不存在就报错
        if err !=nil{
            fmt.Println("出错啦",err)
        }
        b:=make([]byte,3)
            for {
                _, err1 := f.Read(b)
                if err1 == io.EOF {
                    fmt.Println(string(b))
                    break
                } else if err1 != nil {
                    fmt.Println("粗错啦")
                    break
                } else {
                    fmt.Println(string(b))
                }
            }
    

    3.按行读

    f,err:=os.Open("./log.text")
    	if err !=nil{
    			fmt.Println("出错啦",err)
    		}
    	s:=bufio.NewScanner(f)
    	for s.Scan(){
    		fmt.Println(s.Text())
    	}
    

    4.创建(存在就清空)

    fileobj, _ := os.Create("./creat.test")  //OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
    writeString, _ := fileobj.WriteString("哈哈哈
    ")
    fmt.Println(writeString)
    

    5.append追加

    f,_:=os.OpenFile("./log.text",os.O_CREATE|os.O_APPEND|os.O_RDWR,0666)
    	for i:=0;i<10;i++{
    		f.WriteString(fmt.Sprintf("哈哈哈%d
    ",i))
    	}
    
    永远不要高估自己
  • 相关阅读:
    基于Andoird 4.2.2的同步框架源代码学习——同步发起端
    C#MD5为密码加密
    YOUYOU深入学习Ganglia之三(gmetad的软件架构)
    js原生appendChild的bug
    Spring MVC 教程,快速入门,深入分析
    Centos 6.4 Linux 相关问题总结
    jQuery插件之-瀑布流插件
    编辑简单的 shell程序
    Qt国际化相关类
    三层架构与MVC
  • 原文地址:https://www.cnblogs.com/liqiangwei/p/14630085.html
Copyright © 2011-2022 走看看