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))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 添加组件无法加载页面,某块加载卡住
  • ¥15 网络科学导论,网络控制
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错