Go Series Tutorial--35. Read file

Source: Internet
Author: User
Tags file handling readfile tag name
! [Reading Files] (https://raw.githubusercontent.com/studygolang/gctt-images/master/golang-series/golang-read-files.png) Welcome to [ Golang Series Tutorial] (HTTPS://STUDYGOLANG.COM/SUBJECT/2) the 35th chapter. File reads are one of the most common operations in all programming languages. In this tutorial we will learn how to read files using Go. This tutorial is divided into the following subsections. -Read entire file to memory-use absolute file path-use command line tag to pass file path-bind file in binary file-block read file-line read File # # to read the entire file into memory the entire file is read into memory, and the most basic file operation is one. This requires [' ReadFile ' in the [' Ioutil '] (https://golang.org/pkg/io/ioutil/) package (https://golang.org/pkg/io/ioutil/#ReadFile) Function. Let's read a file in the same directory as the Go program. I have created a folder in the Gopath (original is goroot, should be a clerical error), inside that folder, there is a text file ' Test.txt ', we will use the Go program ' Filehandling.go ' to read it. ' Test.txt ' contains the text "Hello world." Welcome to file handling in Go ". The structure of my folder is as follows: "' src filehandling filehandling.go test.txt" Then let's take a look at the code. "' Gopackage mainimport (" FMT "" Io/ioutil ") func main () {data, err: = Ioutil. ReadFile ("test.txt") if err! = Nil {fmt. Println ("File reading Error", err) return} FMT. Println ("Contents of File:", String (data)} "because the file cannot be read on playground, run this program in your local environment. In line 9th of the above program, the program reads the file and returns a Byte [slice] (https://studygolang.com/articles/12121), and this slice is saved in ' data '. In line 14th, we convert ' data ' to ' string ' to show the contents of the file. Please run the program in the location where the **test.txt** is located. For example, for **linux/mac**, if **test.txt** is located in **/home/naveen/go/src/filehandling**, you can use the following steps to run the program. "' bash$ cd/home/naveen/go/src/filehandling/$ go install filehandling$ workspacepath/bin/filehandling" for **windows * *, if **test.txt** is located in **c:\users\naveen.r\go\src\filehandling**, use the following steps. "' Bash> CD c:\users\naveen.r\go\src\filehandling> go install filehandling> workspacepath\bin\ Filehandling.exe "' This program will output: ' Bascontents of File:hello world. Welcome to file handling in Go. "If you run the program in another location (such as '/home/userdirectory '), the following error will be printed. "Bashfile reading error open Test.txt:The system cannot find the file specified." This is because Go is a compiled language. ' Go install ' will create a binary file based on the source code. The binaries are independent of the source code and can be run in any location. Because the ' test.txt ' was not found at the location where the binaries were run, the program will error, prompting that the specified file cannot be found. There are three ways to solve this problem. 1. Use absolute file path 2. Use the command line tag to pass the file path 3. Bind the files in a binary file let's go through this in turn. # # 1. The simplest way to resolve a problem with an absolute file path is to pass in an absolute file path. I have modified the program to change the path to an absolute path. "' Gopackage Mainimport("FMT" "Io/ioutil") func main () {data, err: = Ioutil. ReadFile ("/home/naveen/go/src/filehandling/test.txt") if err! = Nil {fmt. Println ("File reading Error", err) return} FMT. Println ("Contents of File:", String (data)} "can now run the program in any location and print out the contents of ' Test.txt '." For example, you can run it in my home directory. "' bash$ CD $HOME $ go Install filehandling$ workspacepath/bin/filehandling '" The program prints out the contents of ' Test.txt '. It seems like this is a simple method, but its disadvantage is that the file must be placed in the path specified by the program, otherwise it will be an error. # # 2. To pass a file path using a command-line tag another solution is to use a command-line tag to pass a file path. Using the [flag] (https://golang.org/pkg/flag/) package, we can get the file path from the input command line, and then read the file contents. First, let's see how the ' flag ' package works. The ' flag ' package has a [function] (https://studygolang.com/articles/11892) named [' String '] (https://golang.org/pkg/flag/#String). The function receives three parameters. The first parameter is the tag name, the second is the default value, and the third is a short description of the tag. Let's write the program and read the file name from the command line. Replace the contents of ' Filehandling.go ' as follows: ' ' Gopackage mainimport ("Flag" "FMT") func main () {fptr: = flag. String ("Fpath", "test.txt", "file path to read from") flag. Parse () fmt. Println ("Value of Fpath is", *fptr)} "in the above program 8th, through the ' string ' function, created a string token, the name is ' Fpath ', the default value is ' Test.txt ', described as ' file path 'To read from '. This function returns the address of the string [variable] (https://studygolang.com/articles/11756) that stores the flag value. Before the program accesses flag, it must first call ' flag '. Parse () '. In line 10th, the program prints the flag value. Run the program using the following command. "' Bashwrkspacepath/bin/filehandling-fpath=/path-of-file/test.txt ' we passed in '/path-of-file/test.txt ' and assigned the ' Fpath ' tag. The program output: ' Bashvalue of Fpath is/path-of-file/test.txt ' because the default value of ' Fpath ' is ' test.txt '. Now that we know how to read the file path from the command line, let's go ahead and finish our file reading program. "' Gopackage mainimport (" Flag "" FMT "" Io/ioutil ") func main () {fptr: = flag. String ("Fpath", "test.txt", "file path to read from") flag. Parse () data, err: = Ioutil. ReadFile (*FPTR) if err! = Nil {fmt. Println ("File reading Error", err) return} FMT. Println ("Contents of File:", String (data)} "" In the above program, the command line passed in the file path, the program read the contents of the file. Use the following command to run the program. "Bashwrkspacepath/bin/filehandling-fpath=/path-of-file/test.txt" replace '/path-of-file/' with the true path of ' test.txt '. The program will print: "' Txtcontents of File:hello world. Welcome to file handling in Go. "# # 3. Binding a file to a binary file although the way to get the file path from the command line is good, there is a better workaround. Wouldn't it be great if we could bundle a text file in a binary file? That's what we're going to do next.There are many [packages] (https://studygolang.com/articles/11893) that can help us achieve this. We'll use [Packr] (HTTPS://GITHUB.COM/GOBUFFALO/PACKR) because it's simple, and I don't have any problems when I use it in my project. The first step is to install the ' Packr ' package. At the command prompt, enter the following command to install the ' Packr ' package. "' Bashgo get-u github.com/gobuffalo/packr/... ' Packr ' will convert a static file (e.g. '. txt ' file) to '. Go ' file, then the '. Go ' file will be embedded directly into the binary file. ' Packer ' is very smart, and during development, you can get static files from a disk rather than a binary file. During the development process, it is not necessary to recompile when only static files are changed. We get to understand it better through procedures. Replace the ' handling.go ' file with the following: "' Gopackage mainimport (" FMT "" Github.com/gobuffalo/packr ") func main () {box: = Packr. Newbox (".. /filehandling ") Data: = box. String ("Test.txt") fmt. Println ("Contents of File:", data)} "in line 10th of the above program, we created a new box. The box represents a folder whose contents are embedded in the binary. Here, I specify the ' filehandling ' folder, whose contents contain ' Test.txt '. On the next line, we read the contents of the file and print it out. During the development phase, we can use the ' Go Install ' command to run the program. The program can run normally. ' Packr ' is very smart and can load files from disk during the development phase. Use the following command to run the program. "' Bashgo install filehandlingworkspacepath/bin/filehandling" This command can be run in another location. ' Packr ' is smart enough to get the absolute path of the directory passed to the ' newbox ' command. The program will output: "' Txtcontents of File:hello world. Welcome to file handling in Go. ' You can try to change ' tesT.txt ' content, and then run ' filehandling '. As you can see, the program prints out the ' test.txt ' updates without having to compile again. Perfect! :) Now let's take a look at how to package ' test.txt ' into our binaries. We use the ' packr ' command to implement. Run the following command: ' ' Bashpackr install-v filehandling ' It will print: ' ' bashbuilding box. /filehandlingpacking file filehandling.gopacked file filehandling.gopacking file test.txtpacked file test.txtbuilt box: /filehandling with ["Filehandling.go" "" Test.txt "]filehandling" the command binds a static file to a binary file. After running the above command, use the command ' workspacepath/bin/filehandling ' to run the program. The program will print out the contents of ' Test.txt '. So from the binary file, we read the contents of ' Test.txt '. If you do not know whether the file is actually provided by binary or disk, I suggest you remove ' test.txt ' and run the ' filehandling ' command here. You will see that the program prints out the contents of ' Test.txt '. That's great: D. We have successfully embedded a static file in a binary file. # # Block Read the file in the previous chapters, we learned how to read the entire file into memory. It is meaningless to read the entire file into memory when the file is very large, especially if there is insufficient RAM storage. A better approach would be to read the files in chunks. This can be done using the [Bufio] (HTTPS://GOLANG.ORG/PKG/BUFIO) package. Let's write a program that reads ' Test.txt ' files in 3-byte blocks. Replace the contents of ' Filehandling.go ' as shown below. "' Gopackage mainimport (" Bufio "" Flag "" FMT "" Log "" OS ") Func main () {fptr: = flag. String ("Fpath", "test.txt", "file path to read from") flag. Parse () F, err: = OS. Open (*FPTR) if err! = Nil {log. Fatal (ERR)} defer func () {If Err = F.close (); Err! = nil {log. Fatal (Err)}} () R: = Bufio. Newreader (f) B: = make ([]byte, 3) for {_, Err: = R.read (b) if err! = Nil {fmt. Println ("Error reading file:", err) break} fmt. Println (string (b)}} "" In line 15th of the above program, we use the command line tag to pass the path to open the file. In line 19th, we delay the file closing operation. In line 24th of the above program, we have created a new buffer reader (buffered reader). On the next line, we create a byte slice with a length and a capacity of 3, and the program reads the bytes of the file into the slice. The ' read ' [method] (https://studygolang.com/articles/12264) of line 27th reads len (b) bytes (up to 3 bytes) and returns the number of bytes read. When the file is finally reached, it returns an EOF error. Other parts of the program are relatively simple and do not explain. If we use the following command to run the program: "bash$ go install filehandling$ wrkspacepath/bin/filehandling-fpath=/path-of-file/test.txt" will get the following output: "' Bashhelloworld. Welcometofile Handling in Go.error reading file:eof "' # # Read the file by line This section we discuss how to use Go to read a file line by row. This can be achieved using [Bufio] (https://golang.org/pkg/bufio/). Please replace ' test.txt ' with the following content. "' Hello world. ' Welcome to file handling in Go.this are the second line of the file. We have reached the end of the file. "To read files by line involves the following steps. 1. Open the file; 2. In the fileCreate a new scanner;3 on the Scan the files and read them line by row. Replace ' Filehandling.go ' with the following content. "' Gopackage mainimport (" Bufio "" Flag "" FMT "" Log "" OS ") Func main () {fptr: = flag. String ("Fpath", "test.txt", "file path to read from") flag. Parse () F, err: = OS. Open (*FPTR) if err! = Nil {log. Fatal (ERR)} defer func () {If Err = F.close (); Err! = nil {log. Fatal (Err)}} () s: = Bufio. Newscanner (f) for S.scan () {fmt. Println (S.text ())} err = S.err () if err! = Nil {log. Fatal (Err)}} "in line 15th of the above program, we use the command line to mark the incoming path and open the file. In line 24th, we created a new scanner with the file. The ' Scan () ' method of line 25th reads the next line of the file, and if it can be read, you can use the ' Text () ' method. When ' scan ' returns false, ' err () ' Returns the error that occurred during the scan unless the end of the file has been reached (' err () ' returned ' nil '). If I use the following command to run the program: "bash$ go install filehandling$ workspacepath/bin/filehandling-fpath=/path-of-file/test.txt" The program will output: "' Bashhello world. Welcome to file handling in Go.this are the second line of the file. We have reached the end of the file. "This tutorial concludes. I hope you enjoy it and have a good time. * * Previous Tutorial * *-[reflection] (https://studygolang.com/articles/13178)

via:https://golangbot.com/read-files/

Author: naveen Ramanathan Translator: Noluye proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

430 Reads
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.