This is a creation in Article, where the information may have evolved or changed.
Read and write files, do not add file path, default write to Gopath path
Terminal Read and write:
Source
string string, a ... Interface int , err Error)
Explanation: SSCANF scans the argument string, storing successive space-separated values into successive arguments as determined by The format.
It returns the number of items successfully parsed. Newlines in the input must match newlines in the format.
Package Mainimport"FMT"//terminal reading and writingType Studentstruct{Namestring Ageintscore Float32}func Main () {varstr ="stu01 89.92" varStu student FMT. SSCANF (str,"%s%d%f", &stu. Name, &stu. Age, &Stu. Score) FMT. Println (Stu)}
Text I/O buffering:
Source
*newdefault size.
-
Package Mainimport ("Bufio" "FMT" "OS"Func Main () {reader:=Bufio. Newreader (OS. Stdin) str, err:= Reader. ReadString ('\ n') ifErr! =Nil {fmt. Println ("Read String,err:", Err)return} fmt. Printf ("Read STR succ,ret:%s\n", str)}
Open file, read
Package Mainimport ("Bufio" "FMT" "OS")//Read FileFunc Main () {//Open a fileFile, err: = OS. Open ("D:/project/src/go_dev/day7/example4/123.log") ifErr! =Nil {fmt. Println ("Read file err:", Err)return } //focus, file to closedefer file. Close ()/*func newreadersize func newreadersize (rd IO. Reader, size int) *reader newreadersize returns a new Reader whose buffer has at least the specified size. If the argument io. Reader is already a reader with large enough size, it returns the underlying reader. */Reader:=Bufio. Newreader (file)
If the file is not wrapped at the end, error str, err:= Reader. ReadString ('\ n') ifErr! =Nil {fmt. Println ("Read string Failed,err:", Err)return} fmt. Printf ("Read STR success,result:%s\n", str)}
ReadString Source
/* func (*reader) Readstring¶func (b *reader) ReadString (Delim byte) (string, error) ReadString reads until the Firs T occurrence of Delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error Itse LF (often io. EOF). ReadString returns ERR! = Nil if and only if the returned data does not end in Delim. For simple uses, a Scanner is more convenient. */
-read the number of characters in a row
Package Mainimport ("FMT" "OS")/*reads a line of strings from the terminal, counting the number of English, numbers, spaces, and other characters*/Import ("Bufio" "io") Type CharCountstruct{ChcountintNumcountintSpacecountintOthercountint}func Main () {file, err:= OS. Open ("D:/project/src/go_dev/day7/example4/123.log") ifErr! =Nil {fmt. Println ("Read file err:", Err)return} defer file. Close ()varCount CharCount Reader:=Bufio. Newreader (file) for{str, err:= Reader. ReadString ('\ n') ifErr = =io. EOF { Break } ifErr! =Nil {fmt. Printf ("Read File Failed,err:%v", Err) Break} Runearr:=[]rune (str) for_, V: =Range Runearr {Switch { CaseV >='a'&& v <='Z': Fallthrough CaseV >='A'&& v <='Z': Count. Chcount++ Casev = =' '|| v = ='\ t': Count. Spacecount++ CaseV >='0'&& v <='9': Count. Numcount++default: Count. Othercount++}}} fmt. Printf ("Char count:%d\n", Count. Chcount) fmt. Printf ("Num count:%d\n", Count. Numcount) fmt. Printf ("Space count:%d\n", Count. Spacecount) fmt. Printf ("Other count:%d\n", Count. Othercount)} Character Statistics
File Write
--
Package Mainimport ("Bufio" "FMT" "OS") Func main () {outputfile,outputerror:=os. OpenFile ("Output.dat", OS. O_wronly|os. O_create,0666) ifoutputerror!=nil{FMT. Printf ("An error occurred with file Crea ion\n") return } //be sure to close before the function is finished, and rememberdefer outputfile.close () Outputwriter:=Bufio. Newwriter (outputFile) outputstring:="Hello world!\n" fori:=0;i<Ten; i++{outputwriter.writestring (outputstring)} outputwriter.flush ()//Refresh Floor}
Copy files for Golang
Package Mainimport ("FMT" "io" "OS") Func main () {//os. Args is a slice of string that is used to store all command-line argumentsW, err: = CopyFile (OS. args[1], OS. args[2]) ifErr! =Nil {fmt. Println (Err. Error ())} FMT. Println (W)}func CopyFile (DstName, SrcNamestring) (written int64, err error) {src, err:=OS. Open (SrcName)ifErr! =Nil {return} defer src. Close () DST, err:= OS. OpenFile (DstName, OS. O_wronly|os. O_create,0644) ifErr! =Nil {return} defer DST. Close ()//write the src content into DST returnio. Copy (DST, SRC)}
Command-line arguments
Package Mainimport ( "fmt" "os") func Main () { fmt. Printf ("len of args:%d\n", Len (OS). Args)) for I, V: = range OS. Args { FMT. Printf ("args[%d]=%s\n", I, v) }}
The flag package is used to implement command-line arguments
For example, Ls-l under Linux
Package Mainimport ("Flag" "FMT")//Flag Package supports command-line argumentsFunc Main () {varConfpathstring varLogLevelintflag. Stringvar (&confpath,"C","","Please input conf path") flag. Intvar (&loglevel,"D",0,"Please INPUT LOG level") flag. Parse () fmt. Println ("Path:", Confpath) fmt. Println ("log leve:", LogLevel)}