Go file handling

The file processing in the go language is generally in the os package

func Mkdir(name string, perm FileMode) error

Create a directory named name, and the permission setting is perm, such as 0777

func MkdirAll(path string, perm FileMode) error

Create multi-level subdirectories based on path, such as astaxie/test1/test2.

func Remove(name string) error

Delete the directory named name, an error occurs when there are files or other directories in the directory

func RemoveAll(path string) error

Delete multi-level subdirectories according to path. If path is a single name, then all subdirectories under the directory are deleted.

package main

import (
	"fmt"
	"os"
)

func main() {
	os.Mkdir("ff", 0777)
	os.MkdirAll("ff/test1/test2", 0777)
	err := os.Remove("ff")
	if err != nil {
		fmt.Println(err)
	}
	os.RemoveAll("ff")
}

func Create(name string) (file *File, err Error)

Create a new file according to the provided file name, return a file object, the default permission is 0666 file, the returned file object is readable and writable.

func NewFile(fd uintptr, name string) *File

Create the corresponding file according to the file descriptor and return a file object

func Open(name string) (file *File, err Error)

This method opens a file named name, but it is read-only. The internal implementation actually calls OpenFile.

func OpenFile(name string, flag int, perm uint32) (file *File, err Error)

Open the file named name, flag is the way to open, read-only, read-write, etc., perm is the permission

func (file *File) Write(b []byte) (n int, err Error)

Write byte type information to the file

func (file *File) WriteAt(b []byte, off int64) (n int, err Error)

Start writing byte type information at the specified position

func (file *File) WriteString(s string) (ret int, err Error)

write string information to file

package main

import (
	"fmt"
	"os"
)

func main() {
	userFile := "ff.txt"
	fout, err := os.Create(userFile)		
	if err != nil {
		fmt.Println(userFile, err)
		return
	}
	defer fout.Close()
	for i := 0; i < 10; i++ {
		fout.WriteString("Just a test!\r\n")
		fout.Write([]byte("Just a test!\r\n"))
	}
}

func (file *File) Read(b []byte) (n int, err Error)

read data into b

func (file *File) ReadAt(b []byte, off int64) (n int, err Error)

Read data from off to b

package main

import (
	"fmt"
	"os"
)

func main() {
	userFile := "ff.txt"
	fl, err := os.Open(userFile)		
	if err != nil {
		fmt.Println(userFile, err)
		return
	}
	defer fl.Close()
	buf := make([]byte, 1024)
	for {
		n, _ := fl.Read(buf)
		if 0 == n {
			break
		}
		os.Stdout.Write(buf[:n])
	}
}

func Remove(name string) Error

Call this function to delete the file named name

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326434430&siteId=291194637