Detailed knowledge of file operation

Detailed knowledge of file operation

One, flow ,

1. Definition: the path from the data source (file) to the program (memory);
2. Input stream and output stream: the input stream is to write a file (the path from the file to the memory), and the output stream is to read the file (the path from the memory to the file) );
3. os.File encapsulates all file operations, File is a structure;

Two, open and close files

func main(){
    
    
	file,err:=os.Open("G:\\Goproject\\goFile.txt")
	defer file.Close()   //关闭文件句柄
	if err!=nil{
    
    
		fmt.Println("文件句柄获取错误")
		return
	}
	fmt.Println(file)    //这里获得文件的句柄,是指针类型
}

Three, read the file

The file is read with a buffer. When reading, you need to create a buffer bufio.NewReader()and then use the ReadString function in the buffer to set the end of the file to read and read the file.

func Read(){
    
    
	file,err:=os.Open("G:\\Goproject\\goFile.txt")
	defer file.Close()
	if err!=nil{
    
    
		fmt.Println("文件路径发生错误")
	}
	reader:=bufio.NewReader(file)  //建立文件缓冲区
	for{
    
    
		str,err:=reader.ReadString('\n')
		fmt.Println(str)
		if err==io.EOF{
    
    
			fmt.Println("文件读取完毕")
			break
		}
	}
}

Four, write files

When writing a file, you need to use the os.OpenFile method
Insert picture description here
. The first parameter is the file path name, the second parameter is as shown in the figure below, and the third parameter is the
Insert picture description here
same as when reading the file on the Linux system. Write the file At the same time, you need to create a buffer, and then use the WriteString method of the buffer, but because it is buffered data, you need to use the Flush method to flush

func Write(){
    
    
	file,err:=os.OpenFile("G:\\Goproject\\goFile1.txt",os.O_WRONLY|os.O_RDONLY|os.O_CREATE,0666)
	defer file.Close()
	if err!=nil{
    
    
		fmt.Println("打开文件获取句柄失败")
	}
	writer:=bufio.NewWriter(file)//建立缓冲区
	for i:=0;i<5;i++{
    
    
		writer.WriteString("hello")
	}
	writer.Flush()
}

File coverage, adding content only needs to modify the second parameter, not much explanation here

Five, file copy

File copying needs to use the io.Copy method, io.Copy(reader,writer)reader represents the read buffer, and writer represents the write buffer. You
only need to create a read buffer for the file to be copied, create a write buffer for the copy point file, and call the method.

If reading this article is helpful to you, please like and support, thank you

Guess you like

Origin blog.csdn.net/yyq1102394156/article/details/114085291