1

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?

4
  • 1
    What do you mean by "open"? Read it? Write it? Render it? Commented Feb 15, 2014 at 15:17
  • @gongzhitaao hi! I want to open it. Eg. when I run a certain method, my HTML file will be launched in mozilla or chrome. :D Commented Feb 15, 2014 at 15:22
  • Might this post be of some help? Commented Feb 15, 2014 at 15:37
  • Why do you want to do that? Commented Feb 15, 2014 at 19:51

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.