golang 建立、讀取、寫入文件

1、golang建立文本文件

        f,err := os.Create( fileName )golang

        defer f.Close()app

        if err !=nil {dom

            fmt.Println( err.Error() )socket

        } else {ui

            _,err=f.Write([]byte("要寫入的文本內容"))spa

            fmt.Println( err.Error() )ip

        }同步

 

2、golang讀取文本文件

        f, err := os.OpenFile(fileName, os.O_RDONLY,0600)string

        defer f.Close()it

        if err !=nil {

            fmt.Println(err.Error())

        } else {

            contentByte,err=ioutil.ReadAll(f)

            fmt.Println( string(contentByte), err.Error() )

        }

        OpenFile用法:os.OpenFile(文件名,打開方式,打開模式)

        //打開方式

        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.

        )

        //打開模式

        const (

            ModeDir FileMode = 1 << (32 - 1 - iota) // d: is a directory 文件夾模式

            ModeAppend // a: append-only 追加模式

            ModeExclusive // l: exclusive use 單獨使用

            ModeTemporary // T: temporary file (not backed up) 臨時文件

            ModeSymlink // L: symbolic link 象徵性的關聯

            ModeDevice // D: device file 設備文件

            ModeNamedPipe // p: named pipe (FIFO) 命名管道

            ModeSocket // S: Unix domain socket Unix 主機 socket

            ModeSetuid // u: setuid 設置uid

            ModeSetgid // g: setgid 設置gid

            ModeCharDevice // c: Unix character device, when ModeDevice is set Unix 字符設備,當設備模式是設置Unix

            ModeSticky // t: sticky 粘性的

            // Mask for the type bits. For regular files, none will be set. bit位遮蓋.不變的文件設置爲none

            ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice

            ModePerm FileMode = 0777 // Unix permission bits 權限位.

        )

 

3、golang寫入文本文件

        f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_TRUNC, 0600)

        defer f.Close()

        if err != nil {

            fmt.Println( err.Error() )

        } else {

            _,err=f.Write([]byte("要寫入的文本內容"))

            fmt.Println( err.Error() )   

        }

相關文章
相關標籤/搜索