Golang Copy Tool

160 Views Asked by At

Hey if have been working on this copy tool as an exercise since I am totally new to Golang and programming. So far it does work in the way i want but I am trying to do fine cuts on it. The Tool asks for a source path and my Code adds an "\" for comfort, but I want the program to ignore whenever I put an "\" at the end of the path or forget to do so. The program should add it by itself in case i forget and ignore in case if there already is one.

The code:

func main() {

    fmt.Println("Willkommen beim Rocon Copy-Tool." +
        "Wählen Sie bitte aus:")
    fmt.Println("Drücken Sie die 1 um einen Dateipfad auszuwählen")
    fmt.Println("Drücken Sie die 2 um das Programm zu beenden")

    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    input := scanner.Text()

    if input == "1" {


        fmt.Print("Geben Sie den gewünschten Dateipfad an: ")

        scanner = bufio.NewScanner(os.Stdin)
        scanner.Scan()
        srcPath := scanner.Text()

        fmt.Print("Geben Sie den gewünschten Dateinamen an: ")
        scanner.Scan()
        filename := scanner.Text()

        // Open the source file
        srcFile, err := os.Open(srcPath+ "\\" + filename)
        if err != nil {
            log.Fatal(err)
        }
        defer srcFile.Close()

        // Create the destination file
        fmt.Print("Geben Sie den gewünschten Speicherort an: ")
        scanner.Scan()
        scanner.Text()
        dstPath := scanner.Text()

        dstFile, err := os.Create(dstPath + filename)
        if err != nil {
            log.Fatal(err)
        }
        defer dstFile.Close()

        // Copy the file
        _, err = io.Copy(dstFile, srcFile)
    }
}

I hope the German query don't bother while reading it.

1

There are 1 best solutions below

0
Hector Correa On

As kostix indicated I think filepath.Join is your best bet for this.

This line:

srcFile, err := os.Open(srcPath+ "\\" + filename)

Would become:

srcFile, err := os.Open(filepath.Join(srcPath, filename))

(you'll need to import "path/filepath")

You can do the same for the the destination file.