我想运行我的go文件,当我输入go run命令时input.txt,我的go程序将读取input.txt文件,即:
go run goFile.go input.txt
Run Code Online (Sandbox Code Playgroud)
我不想放入input.txt我的goFile.go代码,因为我的go文件不应该只在任何输入名称上运行input.txt.
我尝试ioutil.ReadAll(os.Stdin)但我需要改变我的命令
go run goFile.go < input.txt
Run Code Online (Sandbox Code Playgroud)
我只用包fmt,os,bufio和io/ioutil.没有任何其他包装可以做到吗?
请查看io/ioutil您已经使用的软件包文档.
它具有完全适用于此的功能: ReadFile()
func ReadFile(filename string) ([]byte, error)
Run Code Online (Sandbox Code Playgroud)
用法示例:
func main() {
// First element in os.Args is always the program name,
// So we need at least 2 arguments to have a file name argument.
if len(os.Args) < 2 {
fmt.Println("Missing parameter, provide file name!")
return
}
data, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Println("Can't read file:", os.Args[1])
panic(err)
}
// data is the file content, you can use it
fmt.Println("File content is:")
fmt.Println(string(data))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5828 次 |
| 最近记录: |