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 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效