How to execute file created by my program?

Viewed 42

I'm trying to execute .ics file that my program just created. Basically, my program is simple CLI calendar app, which generates .ics file. It would be nice if my program would execute this file and add it straight to OS calendar app, without unnecessary searching and executing through OS GUI. I paste main function to better understanding.

func main() {

    serialized, name := cal()

    f, err := os.Create(name + ".ics")
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    _, err2 := f.WriteString(serialized)
    if err2 != nil {
        log.Fatal(err2)
    }
    cmd := exec.Command(name + ".ics")
    err = cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
}

As it's shown I tried with exec.Command, but it doesnt' work. I was even trying with additional prefixes like ./ or ~/, but it as well didn't work.

Error messages:

fork/exec ./Meeting.ics: permission denied

exec: "Meeting.ics": executable file not found in $PATH

So to sum it up - I want to skip the process where the user has to find a file and open it. I want to make it automatically as a part of my application.

Here's my repository if it would help https://github.com/lenoopaleno/golang-calendar

I'm working on WSL 2, Ubuntu 22.04

1 Answers

Beside the comments above, you might have a problem in your code with the defer f.Close()

The defer runs when the function ends. Until that time your file might or might not be closed and accessible by a different process. Second you will most likely have to set an execute flag on the a program to run under unix style operating systems.

Program adjustment:

func main() {

    serialized, name := cal()

    f, err := os.Create(name + ".ics")
    if err != nil {
        log.Fatal(err)
    }

    _, err2 := f.WriteString(serialized)
    if err2 != nil {
        log.Fatal(err2)
    }
    f.Sync()
    f.Close()
    exec.Command(`chmod +x `+name+".ics").Run() // This can be done prettier
    cmd := exec.Command(name + ".ics")
    err = cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
}
Related