Golang file Operations

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Operation file is any programming language is not around, to master a language, know how to manipulate the file is essential, today learned the next Golang to file operation support.

Golang support for files is in the OS package. I have no intention of writing this article as an official document, I just want to discuss how to manipulate the files using these interfaces.

OPEN

Func OpenFile (name string, flag int, perm FileMode) (file *file, err Error)

We see flags and FileMode. For example, I want to read and write open a file, if it does not exist to create, if present, append write, how to write go code?

F,err: = os. OpenFile ("Test.txt", OS. O_create|os. O_append|os. o_rdwr,0660) if (err! = nil) {Panic (ERR)}

CLOSE

This interface has nothing to say. The interface is as follows

Func (f *file) Close () error

but said the interface does not say, but Golang provides defer, this is a I think is very good features, is to do cleanup put to defer to do. go provides defer to solve this dilemma, without having to worry about close at all times, before the function exits, it executes close

F,err: = os. OpenFile ("Test.txt", OS. O_create|os. O_append|os. o_rdwr,0660) if (err! = nil) {Panic ("Open file Failed")} defer F.close () ...

Read and Write

The interface is as follows

Func (f *file) Read (b []byte) (n int, err Error) func (f *file) ReadAt (b []byte, off Int64) (n int, err Error) func (f *file Write (b []byte) (n int, err Error) func (f *file) writeat (b []byte, off Int64) (n int, err Error) func (f *file) Writestri Ng (S string) (ret int, err error)

To see the code snippet, learn to use the read-write interface:

Read_buf := make ([]byte,32)     var pos int64 = 0     for{        n,err := f.readat (Read_buf,pos)         if err != nil && err !=  io. Eof{            panic (ERR)          }        if n == 0{             fmt. Printf ("\nfinish read\n")             break         }        fmt. Printf ("%s", String (Read_buf[:n]))         pos = pos + ( Int64) (n)     }

   Looking at a code snippet:

 var buff = make ([]byte,1024)     for{        n,err := fi. Read (Buff)         if err != nil &&  Err != io. Eof{            panic (ERR)          }                 if n == 0{             break        }        if  _,err := fo. Write (Buff[:n]); err != nil{             panic (Err)         }    } 

  

package mainimport  "FMT" import  "OS" import  "IO" func usage () {     Fmt. Printf ("%s %s %s\n", OS. Args[0], "filename"  ,  "NewFile")}func main () {        if  len (OS. Args)  != 3{        usage ()          return     }    filename_in := os. Args[1]    fi,err := os. Open (filename_in)     if err != nil{         panic (Err)     }    defer fi. Close ()     filename_out := os. Args[2]    fo,err := os. Create (filename_out)     if err != nil{         panic (ERR)     }     defer fo. Close ()     var buff = make ([]byte,1024)     for{         n,err := fi. Read (Buff)         if err != nil &&  Err != io. Eof{            panic (ERR)          }                 if n == 0{             break        }        if  _,err := fo. Write (Buff[:n]); err != nil{             panic (Err)         }    }}

Execution results

manu@manu-hacks:~/code/go/self$./mycp test.txt test.bakmanu@manu-hacks:~/code/go/self$ diff test.txt Test.bak manu@manu-hacks:~/code/go/self$ Cat Test.txt This was test file created by GOif not existed, please create this fileif exis Ted, please write Appendhello world,hello gothis was test file created by GOif no existed, please create this fileif exist Ed, please write Appendhello World,hello go


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.