Golang读取输入文件时出现打开失败错误的问题求助
大家好,我刚接触Golang,最近在做一个编码挑战,下载了对应的代码片段后仔细读了附带的README.md文件。按照说明运行run.bat后,成功生成了geektrust.exe可执行文件,但当我尝试用go run main.go ./geektrust sample_input/input1.txt命令直接运行源码时,程序总是输出“Error opening the input file”的错误提示。
我已经确认sample_input/input1.txt是标准的文本文件,但就是无法正常打开读取,想请教下各位我哪里操作错了?
以下是我的相关文件内容:
main.go源码
package main import ( "bufio" "fmt" "os" ) func main() { cliArgs := os.Args[1:] if len(cliArgs) == 0 { fmt.Println("Please provide the input file path") return } filePath := cliArgs[0] file, err := os.Open(filePath) if err != nil { fmt.Println("Error opening the input file") return } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { /* args := scanner.Text() argList := strings.Fields(args) Add your code here to process the input commands */ } }
README.md中的运行说明
Pre-requisites
- Go 1.15.7/1.16.8/1.17
- go tool
How to run the codeWe have provided scripts to execute the code.
Userun.shif you are Linux/Unix/macOS Operating systems andrun.batif you are on Windows. Both the files run the commands silently and prints only output from the input filesample_input/input1.txt. You are supposed to add the input commands in the file from the appropriate problem statement.Internally both the scripts run the following commands
go build .- This will build an executable by the name geektrust in the directory $GOPATH/src/geektrust besides the main.go file .- Execute the file from the directory $GOPATH/src/geektrust using the command
./geektrust sample_input/input1.txtWe expect your program to take the location to the text file as parameter. Input needs to be read from a text file, and output should be printed to the console. The text file will contain only commands in the format prescribed by the respective problem.
备注:内容来源于stack exchange,提问作者SHUBHAM

