How do I open a file with my own program and have it invoke another program?

task: I would like to create my own file extension so that when I click on a particular "dot" file, my program will open it. However, this program I wrote, is just a middle-man in that it will do some processing, but ultimately pass that file onto another program for processing.

example: So for example, all plain text files with the extension .foo will appear as though they are being opened with gedit. But what is really happening, is that they are being opened with one of my programs, and in turn, my program passes that file onto gedit.

my c++ program to do this, looks like this:

#include <string>
#include <cstdlib>

int main(int argc,  char** argv) {

    //open file with gedit
    system(("(gedit " + std::string(argv[1]) + " > /dev/null &)").c_str());

    //do other processing
    //...
}

I believe that when you click on a file and the operating system tells it to be opened with a certain program, that file name is passed to a c++ program as the 2nd argument of that program(as index 1, since index zero is the program's name). The & is so that gedit is run as a background process, and the extra () around the statement ensures that gedit will not be closed when the parent shell is closed.

problem: With all that being said, this program works correctly when I have the binary sitting in a folder that is listed in my $PATH variable and I run the program from the command line passing in the file as if it were clicked. However, it does not work when I actually set the file to be opened with the program.

how I've set up running a program on file click: I ran the script found in the answer of this question, and the program DOES show up when I Right Click->Properties->Open With but nothing appears to happen when I click the file. I even put the program in an infinite loop and checked to see if it was running as a process, but it was not. Why is the program not being called at all? Or does it get called and just closes immediately for some reason? Does that script not do everything I needed it to? Are there additional steps I need to take? Should I try to register the program and associate it with the file extension in a different way?

I am on Ubuntu.

Answers


You might just open a terminal and investigate the environment:

int main(int argc,  char** argv) {
    std::system("gnome-terminal");
}

Need Your Help