Vera Aung
Vera Aung

Reputation: 95

Open HTML file in the directory with C++

I want to open the HTML file named "myHTML.html" using C++ code in Ubuntu. The file is located in the same directory as my C++ source files.

May I know how do I do that?

Upvotes: 1

Views: 1681

Answers (1)

First, you could start a process running the web browser (in the background), e.g.

 char cmd[256];
 char mypwd[200];
 memset (mypwd, 0, sizeof(mypwd));
 if (!getcwd(mypwd, sizeof(mypwd))) 
   { perror("getcwd"); exit (EXIT_FAILURE); };
 snprintf (cmd, sizeof(cmd), 
           "/usr/bin/x-www-browser 'file://%s/myHTML.html' &", mypwd);
 int notok = system(cmd);

Of course if the current directory has a weird name (e.g. contains a quote, which is uncommon), you might end up with some code injection. But it is unlikely. and you might replace mypwd with "/proc/self/cwd"

If the HTML file you want to open is builtin, e.g./etc/yourapp/myHTML.html (or some other nice fixed file path, without naughty characters) you could just use

int notok = system("/usr/bin/x-www-browser /etc/yourapp/myHTML.html &");

or

int notok = system("xdg-open  /etc/yourapp/myHTML.html &");

or

pid_t pid = fork();
if (pid == 0) {
   // child process
   execlp("xdg-open", "/etc/yourapp/myHTML.html", NULL);
   _exit(127);
};

(you may want to waitpid for your pid later)

And even better, you could make your C++ application an HTTP server, e.g. with Wt or libonion

Upvotes: 1

Related Questions