Home > Article > Backend Development > Detailed explanation of I/O operations in Go language
The Go language is an open source programming language developed by Google and is designed to focus on simplicity, efficiency, and concurrency performance. In the Go language, I/O operations are a very common and important part. This article will introduce in detail the I/O operations in the Go language, including file reading and writing, network communication, etc., and provide specific code examples.
In Go language, you can use the os.Open
function to open a file for reading operation, example The code is as follows:
package main import ( "fmt" "os" ) func main() { file, err := os.Open("sample.txt") if err != nil { fmt.Println("文件打开失败:", err) return } defer file.Close() buf := make([]byte, 1024) n, err := file.Read(buf) if err != nil { fmt.Println("文件读取失败:", err) return } fmt.Println(string(buf[:n])) }
Use the os.Create
function to create a new file for writing. The sample code is as follows:
package main import ( "fmt" "os" ) func main() { file, err := os.Create("output.txt") if err != nil { fmt.Println("文件创建失败:", err) return } defer file.Close() data := []byte("Hello, World!") _, err = file.Write(data) if err != nil { fmt.Println("文件写入失败:", err) return } fmt.Println("文件写入成功") }
The TCP server can be easily implemented using the net
package. The sample code is as follows:
package main import ( "fmt" "net" ) func handleConnection(conn net.Conn) { defer conn.Close() buf := make([]byte, 1024) n, err := conn.Read(buf) if err != nil { fmt.Println("读取数据失败:", err) return } fmt.Println("接收到客户端数据:", string(buf[:n])) } func main() { listener, err := net.Listen("tcp", "localhost:8888") if err != nil { fmt.Println("TCP服务器启动失败:", err) return } defer listener.Close() fmt.Println("TCP服务器启动成功,监听端口8888") for { conn, err := listener.Accept() if err != nil { fmt.Println("接受连接失败:", err) continue } go handleConnection(conn) } }
The TCP client can also be implemented using the net
package. The sample code is as follows:
package main import ( "fmt" "net" ) func main() { conn, err := net.Dial("tcp", "localhost:8888") if err != nil { fmt.Println("连接服务器失败:", err) return } defer conn.Close() data := []byte("Hello, Server!") _, err = conn.Write(data) if err != nil { fmt.Println("发送数据失败:", err) return } fmt.Println("发送数据成功") }
The above is a detailed introduction to I/O operations in the Go language and specific code examples. I hope it will be helpful to readers. Welcome to continue to pay attention to more articles about the Go language.
The above is the detailed content of Detailed explanation of I/O operations in Go language. For more information, please follow other related articles on the PHP Chinese website!