doushi1964 2019-06-20 01:19
浏览 150
已采纳

我想通过将文件名作为GoLang中的用户输入来读取文件

I have a JSON file called example.json. I need to read this file by taking its name as user input. I have tried with the below code.

func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text,_ := reader.ReadString('
')


    fmt.Println(text)

    file,_ := ioutil.ReadFile(text)
    // os.Exit()
    fmt.Print(file)
}

But It's not working properly. I want to take the JSON file name as a command line input and read the JSON file.

I checked with the below method. But it's not matched with my case.

reader.ReadString does not strip out the first occurrence of delim

  • 写回答

1条回答 默认 最新

  • doutongxuan1614 2019-06-20 02:24
    关注

    First things first. You can figure out why your code doesn't work if you simply deal with the errors properly. You're ignoring the error thrown when you call iotuil.ReadFile(text). Just add the proper treatment and you will have a good clue why it isn't working

    file, err := ioutil.ReadFile(text)
    if err != nil {
        log.Fatal(err)
    }
    

    : no such file or directory

    The reason why your program does not work is likely because there's a break line character in your text variable.

    From Go Documentation

    "ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter."

    Remove the break like character from the variable that holds your user's input and it should work, assuming the input actually matches to a existing file including its correct path.

    func main() {
        reader := bufio.NewReader(os.Stdin)
        fmt.Print("Enter text: ")
        text, _ := reader.ReadString('
    ')
    
        text = strings.TrimSuffix(text, "
    ")
    
        //Add the file path
        //or else the user will be required to enter the entire file location
        f := "path_to_the_file" + text 
    
        file, err := ioutil.ReadFile(f)
    
        if err != nil {
            log.Fatal(err)
        }
    
        fmt.Println(string(file))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 请问这种量表怎么用spss量化分析(作为中介模型的因变量
  • ¥55 AD844 howland电流源如何驱动大额负载
  • ¥15 C++ /QT 内存权限的判断函数列举
  • ¥15 深度学习GFnet理解问题
  • ¥15 单细胞小提琴堆叠图代码
  • ¥50 升级strust2版本到2.3.15.1后使用ognl3.0.6.jar windows环境中没有问题,但部署到linux环境报错
  • ¥15 vue页面,node封装接口
  • ¥15 求TMS320F280039C工程模板!
  • ¥15 delphi+fastreport实现分组补空打印问题
  • ¥15 使用python把两台mysql数据库服务器数据导出和导入