Go file operations

Source: Internet
Author: User

WriteProgramFile operations are not available,Summary:GoLanguage file operations.

1. Create and open

Create a file function:

Func create (name string) (File * file, err error)

Func newfile (FD int, name string) * File

For details, see the official website:Http://golang.org/pkg/ OS /#Create

 

Open the file function:

Func open (name string) (File * file, err error)

Func openfile (name string, flag int, Perm uint32) (File * file, err error)

For details, see the official website:Http://golang.org/pkg/ OS /#Open

 

Ii. Writing files

File writing functions:

Func (File * file) write (B [] Byte) (N int, err error)

Func (File * file) writeat (B [] Byte, off int64) (N int, err error)

Func (File * file) writestring (s string) (Ret int, err error)

For details, see the official website:Http://golang.org/pkg/ OS /#File.Write 

File writing exampleCode:

 PackageMain  Import(  "OS"  "FMT" )  FuncMain (){  Userfile: ="Test.txt"  Fout, err: = OS. Create (userfile)  DeferFout. Close () IfErr! =Nil{  FMT. println (userfile, err)  Return }  ForI: =0; I <10; I ++ {    fout. writestring (   "just a test!    \ r \ n   "  ) Fout. Write ([]Byte("Just a test!\ R \ n"))  }  } 
 
 

Iii. Reading files

File Read functions:

Func (File * file) read (B [] Byte) (N int, err error)

Func (File * file) readat (B [] Byte, off int64) (N int, err error)

For details, see the official website:Http://golang.org/pkg/ OS /#File.Read

Sample Code for reading a file:

 PackageMain  Import( "OS"  "FMT"  )  FuncMain (){  Userfile: ="Test.txt" Fin, err: = OS. Open (userfile)  DeferFin. Close ()  IfErr! =Nil{ FMT. println (userfile, err)  Return  } Buf: =Make([]Byte,1024)  For{ N, _: = fin. Read (BUF)  If0= N {Break}  OS. stdout. Write (BUF [: N]) }  } 
 
 

4. delete an object

Function:

Func remove (name string) Error

For details, see the official website:Http://golang.org/pkg/ OS /#Remove

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.