【问题标题】:os.Open Complaining about invalid argumentos.Open 抱怨无效参数
【发布时间】:2021-05-08 17:35:21
【问题描述】:

我只是在写一个基本的程序来输入文件路径和打开文件但是 os.Open 抛出无效参数

    input_arr := make([]byte, 100)
    for {
        n, err := io.ReadAtLeast(os.Stdin, input_arr, 1)
        if err != nil && err != io.EOF {
            log.Fatal(err)
        }
        //fmt.Print(input_arr[:n])
        //fmt.Printf("%s", input_arr[:n])
        // \n -> 10
        if input_arr[n-1] == 10 {
            fmt.Println("\nEncountered \\n ")
            break
        }
    }

    file_name := string(input_arr)
    fmt.Printf("%T, %s", file_name, file_name)
    f, err := os.Open(file_name)
    fmt.Println(f, err)

代码输出

13:47:46:kumars@kumars-pc:/mnt/c/Users/kumars/git/golang/helloworld$
-> go run go_file.go 
Enter a file path to open: /tmp/hello.txt
Encountered \n 
string, /tmp/hello.txt
<nil> open /tmp/hello.txt
: invalid argument

【问题讨论】:

标签: go


【解决方案1】:

当您创建input_arr := make([]byte, 100) 时,input_arr 中的所有值都设置为其默认值(0 因为byte is a numeric type)。当你用输入中的一些值填充这个数组时,input_arr 中的其他字节将保持原样 (0)。

还有,

<nil> open /tmp/hello.txt
: invalid argument

表示在字符串中还剩下一个换行符,因为错误消息应该如下所示:

<nil> open /tmp/hello.txt: invalid argument

您可以从input_arr 复制填充数据,一切正常:

var data []byte
// ...
for {
    // ...
    if inputArr[n-1] == 10 {
        fmt.Println("\nEncountered \\n ")
        data = inputArr[:n-1]
        break
    }
}

fileName := string(data)

【讨论】:

    猜你喜欢
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多