In the go language, files are used by an OS. The object pointer of the file class is represented, or it can be called, the handle (FileHandle), OS. StdIn and Os.stdout also belong to this *os. of the file type.
The following examples illustrate
Package Main
Import (
"Bufio"
"FMT"
"IO"
"OS"
)
Func Main () {
Inputfile, Inputerror: = OS. Open (OS. ARGS[1])//variable points to the OS. File handle generated when open file opened
If inputerror! = Nil {
Fmt. Printf ("An error occurred on opening the inputfile\n")
Return
}
Defer Inputfile.close ()
Inputreader: = Bufio. Newreader (Inputfile)
Linecounter: = 0
for {
InputString, Readererror: = inputreader.readstring (' \ n ')
InputString, Readererror: = inputreader.readbytes (' \ n ') if readererror = = Io. EOF {
Return
}
linecounter++
Fmt. Printf ("%d:%s", Linecounter, InputString)
}
}
The inputfile in the example above is a *os. A type variable of file that points to an open file descriptor ( file handle). Os. The open function takes a file name as a parameter, and the previous example uses the OS. ARGS[1] The first parameter on the command line, OS. Args[0] refers to the program itself. Use the OS. The open file is read-only, and the other function OpenFile (name string, flag int, perm FileMode) (file *file, err error) refers to more modes of operation. An error occurs when the file to be opened does not exist or if the program does not have sufficient permissions. Defer. The function of the close () function is to ensure that the opened file can be closed before the program is finished. The keyword defer has a deferred execution feature. Through Bufio. Newreader (inputfile), we get a buffered reader. The reason for converting to use reader (or writer) in the Bufio package is that we can use some useful high-level string objects rather than the underlying raw bytes data. Next, using the ReadString (' \ n ') or readbytes (' \ n ') method to read the contents of the file indefinitely, it is worth noting that whether it is a UNIX system or a Windows system, ReadString, Readbytes and ReadLine can be identified as newline by ' \ n '. When we read the file until the end of the file, Readererror!=nil (Readererror==io. EOF), the For loop ends.
There are some alternative ways to do this.
1, can be a string (byte string) to read the contents of a full file at once, io/ioutil the Ioutil in the package. ReadFile () implements this function, which returns a []byte array and nil, or other error, similar to Ioutil, of the bytes it reads. WriteFile writes a []byte to a file.
Two prototypes of functions
Func ReadFile (filename string) ([]byte, error)
Func WriteFile (filename string, data []byte, Perm OS. FileMode) Error
Package Main
Import (
"FMT"
"Io/ioutil"
"OS"
)
Func Main () {
Inputfile: = os. ARGS[1]
OutputFile: = os. ARGS[2]
BUF, err: = Ioutil. ReadFile (Inputfile)
If err! = Nil {
Fmt. fprintf (OS. Stderr, "File Error:%s\n", err)
}
Fmt. Printf ("%s\n", String (BUF))
Err = Ioutil. WriteFile (OutputFile, buf, 0x644)
If err! = Nil {
Panic (err. Error ())
}
}
2, with buffered read files, in addition to using ReadString (), in some cases we are not a line to read a file or two files, we can use Bufio. The read () method of Reader, in the following manner
BUF: = make ([]byte,1024)//
...
N,err: = Inputreader.read (BUF)
if (n==0) {break}//n is the byte number actually read, the actual number of bytes is returned when the number of bytes in the file is less than the length of the buffer array.
Package Main
Import (
"FMT"
"Io/ioutil"
"Bufio"
"OS"
)
Func Main () {
Inputfile, Inputerror: = OS. Open (OS. ARGS[1])
If inputerror! = Nil {
Fmt. fprintf (OS. Stderr, "File Error:%s\n", Inputerror)
}
FileReader: = Bufio. Newreader (Inputfile)
Counter: = 0
for {
BUF: = Make ([]byte, 1024)
N, _: = Filereader.read (BUF)
counter++
Fmt. Printf ("%d,%s", N, String (BUF))
if n = = 0 {
Break
}
Fmt. PRINTLN (n, buf)
Fmt. Printf ("%d,%s", N, String (BUF))
Fmt. Printf ("/////////////////\n")
}
Fmt. Println (counter)
}
3. Read the column data from the file. If the file is a space-delimited column data, you can use the Fscan series function in the FMT package, which is used in the following example, which assigns values from the read data in the column to the variable v1,v2 and V3, and then appends to an array slice.
Package Main
Import (
"FMT"
"OS"
)
Func Main () {
File, err: = OS. Open (OS. ARGS[1])
If err! = Nil {
Panic (ERR)
}
var col1, col2, col3 []string
for {
VAR v1, v2, v3 string
_, Err: = FMT. Fscanln (file, &v1, &v2, &v3)//FSCANLN will read one line at a time and assign the data for each column to the corresponding variable
If err! = Nil {
Break
}
col1 = Append (col1, v1)
col2 = Append (col2, v2)
col3 = Append (col3, v3)
}
Fmt. Println (col1)
Fmt. Println (col2)
Fmt. Println (COL3)
}
The contents of the file to be read are
A1 A2 A3
B1 B2 B3
C1 C2 C3
Output to
[A1 B1 C1]
[A2 B2 C2]
[A3 b3 C3]
Note: The path package has a sub-package filepath, which provides cross-platform functions for processing file paths and filenames, such as FilePath. Base (Path) returns the last element of the file path.
Import "Path/filepath"
FileName: = filepath. Base (PATH)
File read and write operations in the Go language