On Linux systems, the tail command is used to display the last few lines of one or more files. In development, we often need to use the tail command to view the latest status of the log file in real time. What if we want to implement the functionality of the tail command in the Go language?
In the Go language, we can use the os package and bufio package to implement the tail command. Below is an example of using the Go language to implement the tail command. The code is as follows:
package main import ( "bufio" "flag" "fmt" "os" "time" ) func main() { var filename string var linesNum int flag.StringVar(&filename, "file", "", "file name") flag.IntVar(&linesNum, "n", 10, "last n lines") flag.Parse() if filename == "" { flag.Usage() os.Exit(1) } f, err := os.Open(filename) if err != nil { fmt.Println(err) os.Exit(1) } defer f.Close() fi, err := f.Stat() if err != nil { fmt.Println(err) os.Exit(1) } var offset int64 if fi.Size() > int64(1024*linesNum) { offset = fi.Size() - int64(1024*linesNum) } _, err = f.Seek(offset, 0) if err != nil { fmt.Println(err) os.Exit(1) } reader := bufio.NewReader(f) for { line, _, err := reader.ReadLine() if err != nil { if err.Error() == "EOF" { time.Sleep(time.Second) continue } else { fmt.Println(err) os.Exit(1) } } fmt.Println(string(line)) } }
In the above code, we use the flag package to process command line parameters, the os package to open files, the bufio package to read files, and the time package to implement delays and other operations.
In the program, we receive two command line parameters: the file name and the number of lines to be displayed. If the file name is empty, print instructions and exit the program.
We use the os.Open function to open the file and the f.Stat function to obtain file information. If the file size is larger than the number of lines to be displayed, the file pointer position is set to a position n lines before the end of the file.
We use the bufio.NewReader function to create a buffered reader, and use the ReadLine function in a for loop to read and output each line of the file. If the end of the file is reached, use the time.Sleep function to wait one second and continue reading the file.
Every time we read to the end of the file, we use the time.Sleep function to wait for one second. This is to prevent the program from looping through the file and consuming too much CPU resources. In implementation, we can adjust the waiting time according to actual needs.
In the program, we also use the defer keyword to close the file before the program exits. This is a good practice to ensure resources are released in a timely manner.
The above is a simple example of using the Go language to implement the tail command. Through this example, we can learn how to use the Go language to read files and implement functions similar to the tail command.
The above is the detailed content of Golang implements tail. For more information, please follow other related articles on the PHP Chinese website!