filmov
tv
Go (golang) Tutorials - Command Line Arguments, File I/O

Показать описание
#golang #go #input #output #file
Command line Arguments & File I/O
------------------------------------
= Command Line Arguments
- All the command line arguments will be collected in the os.Args array.
- Args[0] will always contain the binary executable runtime name with the path
- Args[1],Args[2],etc will be used to store the command line arguments in their
given order
- File Output
- WriteFile - Will always create a new file with the given name and content with the permission
provided
----------
package main
import ("fmt"
"os"
)
func main(){
fmt.Println(len(os.Args)) //by default Args array will contain the program runtime as
//command line index 0
fmt.Println(os.Args[1])
}
------------
package main
import (
"io/ioutil"
)
func main(){
data:=[]byte("Hello World\n")
ioutil.WriteFile("myfile",data,0644) //0644 is a read/write permission for a file
//Create or replace the myfile with the given data
}
-----------
package main
import ("fmt"
"io/ioutil"
)
func main(){
data,err:=ioutil.ReadFile("myfile") //Reads data from file, if any errors found returns back
//If an error occurred raise a panic, if not just proceed printing the data
if err!=nil {
panic(err)
}
fmt.Println(string(data))
}
Command line Arguments & File I/O
------------------------------------
= Command Line Arguments
- All the command line arguments will be collected in the os.Args array.
- Args[0] will always contain the binary executable runtime name with the path
- Args[1],Args[2],etc will be used to store the command line arguments in their
given order
- File Output
- WriteFile - Will always create a new file with the given name and content with the permission
provided
----------
package main
import ("fmt"
"os"
)
func main(){
fmt.Println(len(os.Args)) //by default Args array will contain the program runtime as
//command line index 0
fmt.Println(os.Args[1])
}
------------
package main
import (
"io/ioutil"
)
func main(){
data:=[]byte("Hello World\n")
ioutil.WriteFile("myfile",data,0644) //0644 is a read/write permission for a file
//Create or replace the myfile with the given data
}
-----------
package main
import ("fmt"
"io/ioutil"
)
func main(){
data,err:=ioutil.ReadFile("myfile") //Reads data from file, if any errors found returns back
//If an error occurred raise a panic, if not just proceed printing the data
if err!=nil {
panic(err)
}
fmt.Println(string(data))
}
Комментарии