0

I am Just writing a basic program to input file path and open file but os.Open throwing invalid argument

    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)

Output of code

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
Hackaholic
  • 19,069
  • 5
  • 54
  • 72

1 Answers1

1

When you create input_arr := make([]byte, 100) all values in the input_arr are set to its default values (0 because byte is a numeric type). And when you fill this array with some values from an input others bytes in the input_arr are left as they are (0).

Also,

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

indicate that a new-line character also left in the string, because an error message should looks like:

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

You can copy filled data from the input_arr and everything should work:

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

fileName := string(data)