Home > Software design >  Rookie Question: Require user to enter a valid directory in the terminal for input into Go program
Rookie Question: Require user to enter a valid directory in the terminal for input into Go program

Time:11-04

Rookie Question: I'm trying to write a program that takes a directory that is entered into the terminal to perform a later action in the program on that directory. If the user does not enter a directory that exists, how do I get the program to keep asking the user to enter in a valid directory? The error I'm getting on this program is listed at the bottom. I originally tried the fmt.Scan() to get the user input, have now moved onto the bufio scanner, and am at a loss so figured I would ask the experts. Much thanks for any help!

package main

import ( "bufio" "fmt" "os" )

    
fmt.Println("What file path would you like to search?")
    
input := bufio.NewScanner(os.Stdin)

    for input.Scan() {
        text := input.Text()
        x, _ := os.Stat(text)
        if x.IsDir() {
            fmt.Println("Cool this is a directory")
        } else {
            fmt.Println("Sorry, this is not a directory")
            continue

        }

    }
}```

Error:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x48b465]

CodePudding user response:

You could capture the error on the os.Stat() function. The code snippet would look something like this

        x, err := os.Stat(text)
        if err != nil {
            fmt.Println("Re-enter a valid dir:")
            continue
        }

CodePudding user response:

You might want to check the output of the Scan method, and any errors that might have happened there.

According to the documentation:

Scan advances the Scanner to the next token, which will then be available through the Bytes or Text method. It returns false when the scan stops, either by reaching the end of the input or an error. After Scan returns false, the Err method will return any error that occurred during scanning, except that if it was io.EOF, Err will return nil. Scan panics if the split function returns too many empty tokens without advancing the input. This is a common error mode for scanners.

So, try checking out the Err() method for any errors and checking the input.Scan call's return value.

  •  Tags:  
  • go
  • Related