Advertisement
wagner-cipriano

Open a URL from C++ Program

Jun 27th, 2020
1,729
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.47 KB | None | 0 0
  1. /*
  2.   ** Open a URL from C++ Program - multiplatform
  3.   ** Abrir uma url a partir de um programa em c++ (console application)
  4.   ** Tested in linux and windows
  5. */
  6.  
  7. #include <fstream>    //Read and write from a file
  8. #include <string.h>   //strlen
  9. #include <iostream>
  10. using namespace std;
  11.  
  12. bool openFile(ifstream &ifs, const std::string& name);
  13. bool checkFileError(string pathFileErrLog);
  14. bool openUrl(string url);
  15. void checkPlatform();
  16.  
  17. int main() {
  18.   bool r;
  19.   string myUrl = "http://www.travele.com.br";
  20.   checkPlatform();
  21.  
  22.   cout << "Opening " << myUrl;
  23.   r = openUrl(myUrl);
  24.   if(r)
  25.     cout << ": Success";
  26.   else
  27.     cout << ": Error";
  28.  
  29.   return 0;
  30. }
  31.  
  32. // Open a file by path and check the success of the operation
  33. bool openFile(ifstream &ifs, const std::string& name) {
  34.   ifs.open(name.c_str());
  35.   return ifs.is_open();
  36. }
  37.  
  38. //Check error in the command execution
  39. bool checkFileError(string pathFileErrLog) {
  40.   ifstream file;
  41.   string line;
  42.   openFile(file, pathFileErrLog);
  43.   getline(file, line);
  44.   //cout << "\nline: " << line;
  45.   file.close();
  46.   if(strlen(line.c_str()) > 0)
  47.     return false;
  48.   return true;
  49. }
  50.  
  51. //Open an url in the browser
  52. bool openUrl(string url) {
  53.   string pathFileErrLog = "./cmd_err.log", cmd;
  54.   string arrCmd[] = {"CmdErrorTEST", "start", "google-chrome", "firefox"};  //enything else ? put here
  55.   for(int i=0; i<sizeof(arrCmd)/sizeof(arrCmd[0]); i++) {
  56.     cmd = arrCmd[i];
  57.     cmd.append(" "); cmd.append(url); cmd.append(" 2>"); cmd.append(pathFileErrLog);
  58.     system(cmd.c_str());
  59.     if(checkFileError(pathFileErrLog))
  60.       return true;
  61.   }
  62.   return false;
  63. }
  64.  
  65. //Check platform where we are in
  66. void checkPlatform() {
  67.   #ifdef __linux__
  68.     cout << "we're in a linux platform, beautiful!\n\n";
  69.   #else
  70.     cout << "Are you walking in the dark side ?\n\n";
  71.     //Windows fans don't stay angry with me, okay? It is just a joke.
  72.   #endif
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement