Go os, bufio, ioutil packages read and write summaries of files and whether files/folders exist

Read and write to a single file with buffer bufio package


Opens an existing file and overwrites the original content with the new content. There is no need to create a file here so no need to use

os.O_CREATE。
os.O_TRUNC | os.O_WRONLY Open an existing file for writing, clearing the contents of the file before writing.
fileSd,err := os.OpenFile("test.txt",os.O_TRUNC | os.O_WRONLY,os.ModePerm)
	if err != nil{
		fmt.Println("open file error:",err)
		return
	}

	//及时关闭file文件句柄
	defer fileSd.Close()

	//写入的时候,使用带缓存的 *Writer
	writer := bufio.NewWriter(fileSd)

	for i := 0; i < 5; i++{
		writer.WriteString("hh\r\n") //表示换行,为了在记事本和其他编辑器都可以看到换行效果
	}

	writer.Flush()

If you want to append the content of the original file, it is not to overwrite the original file, such as appending when writing the log.

The following is the form of appending, it is not overwriting.

	fileSd,err := os.OpenFile("test.txt",os.O_APPEND | os.O_WRONLY,os.ModePerm)

The next step is to open a file, read the original content and display it in the terminal, and append it. This requires the file to be opened for reading and writing, and open for appending.

The key here is to tell it to open in read-write mode, and write to it in append-to mode when writing.

fileSd,err := os.OpenFile("test.txt",os.O_APPEND | os.O_RDWR,0666)

	reader := bufio.NewReader(fileSd)
	fmt.Println(reader)

	for  {
		content,err := reader.ReadString('\n')
		if err == io.EOF{ //如果读取到文件到末尾就不读了
			break
		}
		fmt.Println(content,err)
	}

 

Without buffer, one-time read and write


Write a program that writes the contents of one file to another file, both of which exist.

Use ioutil.ReadFile / ioutil.WriteFile to complete the task of writing a file.

	filePath := "test.txt"

	//将文件的内容读取到内存,
	content,err := ioutil.ReadFile(filePath)

	if err != nil { //说明读取文件出错了,将错误信息输出,然后退出
		fmt.Println("read fiile error:",err)
		return  //文件读取失败就结束了,不能往下走了
	}

	fmt.Println(string(content))

	//将读取到到内容写入到文件里面
	err = ioutil.WriteFile("test1.txt",content,os.ModePerm)

	if err != nil{
		fmt.Println("write file error:",err)
	}

The idea is actually the same as the following step, open a file, then create a file, and use an infinite loop to continuously write data to the target file from the open file.

  1. srcf = open(src)
  2. dstf= create(dst)
  3. read srcf=>ctx
  4. writer dstf ctx=>
  5. srcf.close dstf.close()

There is a copy function in the io package. This copy function actually reads the content from src and writes it to dst. The following is to continuously read the content from the file and write to the standard output.

	file,_ := os.Open("test.txt")
	defer file.Close()

	io.Copy(os.Stdout,file)

 

Determine whether it is a file or a directory


Manipulate the directory, read the directory.

	path := "test"
	fileSd,err := os.Open(path)
	fmt.Println(fileSd,err)
	if err != nil{
		return
	}
	defer fileSd.Close()

	contents := make([]byte,10)
	n,err := fileSd.Read(contents)
	fmt.Println(n,err)

If it is a directory, the contents inside cannot be read. So here we have to judge whether it is a file or a directory. 

0 read test: is a directory

func (* File)  Stat 

The following is to print the name of the file, determine whether it is a directory, etc. 

 fileInfo,err := fileSd.Stat()
    if err != nil{
    	fmt.Println(err)
	}
	fmt.Println(fileInfo.Name(),fileInfo.IsDir(),fileInfo.Mode(),fileInfo.ModTime().Format("2006-01-02 15:04:05"),fileInfo.Size())


test true drwxr-xr-x 2022-03-22 18:57:19 64

Get information about all files under a directory


func (*File) Readdirnames 

 -1 means to read all the file names under the current folder, and will not read recursively.

 func (*File) Readdir 

	fileInfo,err := fileSd.Readdir(-1)
	for _,v := range fileInfo{
		fmt.Println(v.Name())
	}

Check if the file exists


When performing file operations, sometimes there is such a function to determine whether the file exists, which is often used in the project.

Check if the file exists

Golang's method of judging whether a file or folder exists is to use the error value returned by the os.Stat() function to judge

  1. If the returned error is nil, the file or folder exists
  2. If the returned error type is judged to be true using os.IsNotExist(), the file or folder does not exist
  3. If the returned error is of another type, it is not certain whether it exists or not

func  Stat 

func Stat(name string) (FileInfo, error)

This can define a function by itself, input the path to determine whether the directory or file exists. (Pass in the file path, according to the Boolean value to determine whether the file exists, true means the file/folder exists, otherwise)

func PathExits(path string) (bool,error) {
	_,err := os.Stat(path)

	if err == nil{  //文件或者目录存在
		return true,nil
	}

	if os.IsNotExist(err) {  //判断错误类型是不是不存在类型错误
		return false,nil
	}

	return false,err   //有错误,但是不是上面的错误类型,那么就将错误原封不动的返回
}

Summarize


document

  • Create: os.Create
  • Read: os.0pen 
  • Get properties: os.0pen().Stat/os.Stat
  • Modify attributes: permissions, owner
  • Rename: os.Rename("test1.txt","test2.txt") //Not only can you rename, you can also move files to certain directories os.Rename("test/file1","a/ b/c/file2")
  • Delete file: os.Remove("test1.txt")

There is no copy function! 

content

  • 创建:os.Mkdir("a",os.ModePerm)  os.MkdirAll("a/b/c",os.ModePerm)
  • Read: os.0pen
  • Get properties: os.0pen().Stat/ os.Stat
  • Modify attributes: permissions, owner os.Chmod() os.Chown()
  • Rename: os.Rename
  • Delete a folder: os.Remove os.RemoveAll  

Guess you like

Origin blog.csdn.net/qq_34556414/article/details/123629357