Go file operation

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

The go language supports a lot of file operations
1. Traditional file operation
Package required for import file operation

import"os"

1, the opening of the file

f := os.Open(filepath)

2, the file read

f.Read([]byte)

3. Closing of files

F.close ()

这里写代码片

OpenFile, err: = OS. Open ("Test.go")//correct opening of the file returns ERR: = Nil
//here if the file open exception, throw an error
if err! = Nil {
//panic function terminates the program's run, and the print error is equivalent to C/ The Assert () function in
Panic ("Open File Error")
}
//defer is equivalent to a destructor in C + +, and before the program ends, the function after which it runs
defer openfile. Close ()
//Allocate memory, store read data
Buff: = Make ([]byte, +)
for n, err: = OpenFile. Read (Buff); Err = = Nil; N, err = OpenFile. Read (Buff) {
Fmt. Print (String (buff[:n)))
}
//File load Error, throw exception
If err! = Nil {
Panic (FMT. Sprintf ("Read occurs error:%s", err))
}

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.