Get the App
SLTechnology News&Howtos  ›  Development  › 

The usage of common functions of os library in Go language

Shulou Source: shulou.com Published: 2022-06-03 19:07:03 09月20日 Update

This article mainly explains "the usage of common functions of os library in Go language". The content of the explanation is simple and clear, and it is easy to learn and understand. now please follow the editor's train of thought to study and learn "the usage of common functions of os library in Go language".

(F * File) .Name () this function returns the name of the file. The function prototype func (f * File) Name () string requires the pointer operation of the file and returns a string.

The copy code is as follows:

Func (f * File) Name () string {return f.name}

Import (

"fmt"

"os"

)

Func main () {

F, _: = os.Open ("1.go")

Fmt.Println (f.Name ()) / / output 1.go

}

(F * File) .Read () this is operated by the pointer of the function. It belongs to the method of * FIlE. The function prototype func (f * File) Read (b [] byte) (n int, err error) inputs the number of bytes read and returns the length of bytes and error information.

The copy code is as follows:

Import (

"fmt"

"os"

)

Func main () {

B: = make ([] byte, 100) / / sets the number of bytes read

F, _: = os.Open ("11.go")

N, _: = f.Read (b)

Fmt.Println (n)

Fmt.Println (string (b [: n])) / / Why is the output n instead of entering 100 directly? The underlying layer is implemented in this way.

/ *

N, e: = f.read (b)

If n

< 0 { n = 0 } if n == 0 && len(b) >

0 & & e = = nil {

Return 0, io.EOF

}

, /

/ / so read n if the byte is less than 100

}

(F * File) .ReadAt () the prototype of this function is func (f * File) ReadAt (b [] byte, off int64) (n int, err error) added the subscript, you can customize how much to read.

The copy code is as follows:

Import (

"fmt"

"os"

)

Func main () {

F, _: = os.Open ("11.go")

B: = make ([] byte, 20)

N, _: = f.ReadAt (b, 15)

Fmt.Println (n)

Fmt.Println (string (b [: n]))

}

(F * File) .Readdir () function prototype func (f * File) Readdir (n int) (fi [] FileInfo, err error), we need to open a folder, then set the number of folder files to read, and return the fileinfo information of the file.

The copy code is as follows:

Import (

"fmt"

"os"

)

Func main () {

F, err: = os.Open ("src") / / Open a directory

If err! = nil {

Fmt.Println (err)

}

Defer f.Close ()

Ff, _: = f.Readdir (10) / / sets the number of reads

Tags: Function code file prototype location byte pointer offset output commonly used language content character representative place string learning information name address Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Docker Huawei Microsoft macOS