Author: saqibkhan

  •  Web Programming

    What is CGI?

    • The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script.
    • The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows −
    • The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.
    • The current version is CGI/1.1 and CGI/1.2 is under progress.

    Web Browsing

    To understand the concept of CGI, let’s see what happens when we click a hyperlink to browse a particular web page or URL.

    • Your browser contacts the HTTP web server and demand for the URL ie. filename.
    • Web Server will parse the URL and will look for the filename. If it finds requested file then web server sends that file back to the browser otherwise sends an error message indicating that you have requested a wrong file.
    • Web browser takes response from web server and displays either the received file or error message based on the received response.

    However, it is possible to set up the HTTP server in such a way that whenever a file in a certain directory is requested, that file is not sent back; instead it is executed as a program, and produced output from the program is sent back to your browser to display.

    The Common Gateway Interface (CGI) is a standard protocol for enabling applications (called CGI programs or CGI scripts) to interact with Web servers and with clients. These CGI programs can be a written in Python, PERL, Shell, C or C++ etc.

    CGI Architecture Diagram

    The following simple program shows a simple architecture of CGI −

    CGI Architecture

    Web Server Configuration

    Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI directory and by convention it is named as /var/www/cgi-bin. By convention CGI files will have extension as .cgi, though they are C++ executable.

    By default, Apache Web Server is configured to run CGI programs in /var/www/cgi-bin. If you want to specify any other directory to run your CGI scripts, you can modify the following section in the httpd.conf file −

    <Directory "/var/www/cgi-bin">
       AllowOverride None
       Options ExecCGI
       Order allow,deny
       Allow from all
    </Directory>
     
    <Directory "/var/www/cgi-bin">
       Options All
    </Directory>

    Here, I assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell etc.

    First CGI Program

    Consider the following C++ Program content −

    #include <iostream>
    using namespace std;
    
    int main () {
       cout << "Content-type:text/html\r\n\r\n";
       cout << "<html>\n";
       cout << "<head>\n";
       cout << "<title>Hello World - First CGI Program</title>\n";
       cout << "</head>\n";
       cout << "<body>\n";
       cout << "<h2>Hello World! This is my first CGI program</h2>\n";
       cout << "</body>\n";
       cout << "</html>\n";
       
       return 0;
    }

    Compile above code and name the executable as cplusplus.cgi. This file is being kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program make sure you have change mode of file using chmod 755 cplusplus.cgi UNIX command to make file executable.

    My First CGI program

    The above C++ program is a simple program which is writing its output on STDOUT file i.e. screen. There is one important and extra feature available which is first line printing Content-type:text/html\r\n\r\n. This line is sent back to the browser and specify the content type to be displayed on the browser screen. Now you must have understood the basic concept of CGI and you can write many complicated CGI programs using Python. A C++ CGI program can interact with any other external system, such as RDBMS, to exchange information.

    HTTP Header

    The line Content-type:text/html\r\n\r\n is a part of HTTP header, which is sent to the browser to understand the content. All the HTTP header will be in the following form −

    HTTP Field Name: Field Content
     
    For Example
    Content-type: text/html\r\n\r\n
    

    There are few other important HTTP headers, which you will use frequently in your CGI Programming.

    Sr.NoHeader & Description
    1Content-type:A MIME string defining the format of the file being returned. Example is Content-type:text/html.
    2Expires: DateThe date the information becomes invalid. This should be used by the browser to decide when a page needs to be refreshed. A valid date string should be in the format 01 Jan 1998 12:00:00 GMT.
    3Location: URLThe URL that should be returned instead of the URL requested. You can use this filed to redirect a request to any file.
    4Last-modified: DateThe date of last modification of the resource.
    5Content-length: NThe length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file.
    6Set-Cookie: StringSet the cookie passed through the string.

    CGI Environment Variables

    All the CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program.

    Sr.NoVariable Name & Description
    1CONTENT_TYPEThe data type of the content, used when the client is sending attached content to the server. For example file upload etc.
    2CONTENT_LENGTHThe length of the query information that is available only for POST requests.
    3HTTP_COOKIEReturns the set cookies in the form of key & value pair.
    4HTTP_USER_AGENTThe User-Agent request-header field contains information about the user agent originating the request. It is a name of the web browser.
    5PATH_INFOThe path for the CGI script.
    6QUERY_STRINGThe URL-encoded information that is sent with GET method request.
    7REMOTE_ADDRThe IP address of the remote host making the request. This can be useful for logging or for authentication purpose.
    8REMOTE_HOSTThe fully qualified name of the host making the request. If this information is not available then REMOTE_ADDR can be used to get IR address.
    9REQUEST_METHODThe method used to make the request. The most common methods are GET and POST.
    10SCRIPT_FILENAMEThe full path to the CGI script.
    11SCRIPT_NAMEThe name of the CGI script.
    12SERVER_NAMEThe server’s hostname or IP Address.
    13SERVER_SOFTWAREThe name and version of the software the server is running.

    Here is small CGI program to list out all the CGI variables.

    #include <iostream>
    #include <stdlib.h>
    using namespace std;
    
    const string ENV[ 24 ] = {
       "COMSPEC", "DOCUMENT_ROOT", "GATEWAY_INTERFACE",   
       "HTTP_ACCEPT", "HTTP_ACCEPT_ENCODING",             
       "HTTP_ACCEPT_LANGUAGE", "HTTP_CONNECTION",         
       "HTTP_HOST", "HTTP_USER_AGENT", "PATH",            
       "QUERY_STRING", "REMOTE_ADDR", "REMOTE_PORT",      
       "REQUEST_METHOD", "REQUEST_URI", "SCRIPT_FILENAME",
       "SCRIPT_NAME", "SERVER_ADDR", "SERVER_ADMIN",      
       "SERVER_NAME","SERVER_PORT","SERVER_PROTOCOL",     
       "SERVER_SIGNATURE","SERVER_SOFTWARE" };   
    
    int main () {
       cout << "Content-type:text/html\r\n\r\n";
       cout << "<html>\n";
       cout << "<head>\n";
       cout << "<title>CGI Environment Variables</title>\n";
       cout << "</head>\n";
       cout << "<body>\n";
       cout << "<table border = \"0\" cellspacing = \"2\">";
    
       for ( int i = 0; i < 24; i++ ) {
    
      cout &lt;&lt; "&lt;tr&gt;&lt;td&gt;" &lt;&lt; ENV&#91; i ] &lt;&lt; "&lt;/td&gt;&lt;td&gt;";
      
      // attempt to retrieve value of environment variable
      char *value = getenv( ENV&#91; i ].c_str() );  
      if ( value != 0 ) {
         cout &lt;&lt; value;                                 
      } else {
         cout &lt;&lt; "Environment variable does not exist.";
      }
      cout &lt;&lt; "&lt;/td&gt;&lt;/tr&gt;\n";
    } cout << "</table><\n"; cout << "</body>\n"; cout << "</html>\n"; return 0; }

    C++ CGI Library

    For real examples, you would need to do many operations by your CGI program. There is a CGI library written for C++ program which you can download from ftp://ftp.gnu.org/gnu/cgicc/ and follow the steps to install the library −

    $tar xzf cgicc-X.X.X.tar.gz 
    $cd cgicc-X.X.X/ 
    $./configure --prefix=/usr 
    $make
    $make install
    

    You can check related documentation available at ‘C++ CGI Lib Documentation.

    GET and POST Methods

    You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently browser uses two methods to pass this information to web server. These methods are GET Method and POST Method.

    Passing Information Using GET Method

    The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows −

    http://www.test.com/cgi-bin/cpp.cgi?key1=value1&key2=value2
    

    The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser’s Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation and you can pass upto 1024 characters in a request string.

    When using GET method, information is passed using QUERY_STRING http header and will be accessible in your CGI Program through QUERY_STRING environment variable.

    You can pass information by simply concatenating key and value pairs alongwith any URL or you can use HTML <FORM> tags to pass information using GET method.

    Simple URL Example: Get Method

    Here is a simple URL which will pass two values to hello_get.py program using GET method./cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI

    Below is a program to generate cpp_get.cgi CGI program to handle input given by web browser. We are going to use C++ CGI library which makes it very easy to access passed information −

    #include <iostream>
    #include <vector>  
    #include <string>  
    #include <stdio.h>  
    #include <stdlib.h> 
    
    #include <cgicc/CgiDefs.h> 
    #include <cgicc/Cgicc.h> 
    #include <cgicc/HTTPHTMLHeader.h> 
    #include <cgicc/HTMLClasses.h>  
    
    using namespace std;
    using namespace cgicc;
    
    int main () {
       Cgicc formData;
       
       cout << "Content-type:text/html\r\n\r\n";
       cout << "<html>\n";
       cout << "<head>\n";
       cout << "<title>Using GET and POST Methods</title>\n";
       cout << "</head>\n";
       cout << "<body>\n";
    
       form_iterator fi = formData.getElement("first_name");  
       if( !fi->isEmpty() && fi != (*formData).end()) {  
    
      cout &lt;&lt; "First name: " &lt;&lt; **fi &lt;&lt; endl;  
    } else {
      cout &lt;&lt; "No text entered for first name" &lt;&lt; endl;  
    } cout << "<br/>\n"; fi = formData.getElement("last_name"); if( !fi->isEmpty() &&fi != (*formData).end()) {
      cout &lt;&lt; "Last name: " &lt;&lt; **fi &lt;&lt; endl;  
    } else {
      cout &lt;&lt; "No text entered for last name" &lt;&lt; endl;  
    } cout << "<br/>\n"; cout << "</body>\n"; cout << "</html>\n"; return 0; }

    Now, compile the above program as follows −

    $g++ -o cpp_get.cgi cpp_get.cpp -lcgicc
    

    Generate cpp_get.cgi and put it in your CGI directory and try to access using following link −/cgi-bin/cpp_get.cgi?first_name=ZARA&last_name=ALI

    This would generate following result −

    First name: ZARA 
    Last name: ALI 
    

    Simple FORM Example: GET Method

    Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same CGI script cpp_get.cgi to handle this input.

    <form action = "/cgi-bin/cpp_get.cgi" method = "get">
       First Name: <input type = "text" name = "first_name">  <br />
     
       Last Name: <input type = "text" name = "last_name" />
       <input type = "submit" value = "Submit" />
    </form>

    Here is the actual output of the above form. You enter First and Last Name and then click submit button to see the result.First Name:  Last Name:  

    Passing Information Using POST Method

    A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input.

    The same cpp_get.cgi program will handle POST method as well. Let us take same example as above, which passes two values using HTML FORM and submit button but this time with POST method as follows −

    <form action = "/cgi-bin/cpp_get.cgi" method = "post">
       First Name: <input type = "text" name = "first_name"><br />
       Last Name: <input type = "text" name = "last_name" />
     
       <input type = "submit" value = "Submit" />
    </form>

    Here is the actual output of the above form. You enter First and Last Name and then click submit button to see the result.First Name:  Last Name:  

    Passing Checkbox Data to CGI Program

    Checkboxes are used when more than one option is required to be selected.

    Here is example HTML code for a form with two checkboxes −

    <form action = "/cgi-bin/cpp_checkbox.cgi" method = "POST" target = "_blank">
       <input type = "checkbox" name = "maths" value = "on" /> Maths
       <input type = "checkbox" name = "physics" value = "on" /> Physics
       <input type = "submit" value = "Select Subject" />
    </form>

    The result of this code is the following form − Maths  Physics 

    Below is C++ program, which will generate cpp_checkbox.cgi script to handle input given by web browser through checkbox button.

    #include <iostream>
    #include <vector>  
    #include <string>  
    #include <stdio.h>  
    #include <stdlib.h> 
    
    #include <cgicc/CgiDefs.h> 
    #include <cgicc/Cgicc.h> 
    #include <cgicc/HTTPHTMLHeader.h> 
    #include <cgicc/HTMLClasses.h> 
    
    using namespace std;
    using namespace cgicc;
    
    int main () {
       Cgicc formData;
       bool maths_flag, physics_flag;
    
       cout << "Content-type:text/html\r\n\r\n";
       cout << "<html>\n";
       cout << "<head>\n";
       cout << "<title>Checkbox Data to CGI</title>\n";
       cout << "</head>\n";
       cout << "<body>\n";
    
       maths_flag = formData.queryCheckbox("maths");
       if( maths_flag ) {  
    
      cout &lt;&lt; "Maths Flag: ON " &lt;&lt; endl;  
    } else {
      cout &lt;&lt; "Maths Flag: OFF " &lt;&lt; endl;  
    } cout << "<br/>\n"; physics_flag = formData.queryCheckbox("physics"); if( physics_flag ) {
      cout &lt;&lt; "Physics Flag: ON " &lt;&lt; endl;  
    } else {
      cout &lt;&lt; "Physics Flag: OFF " &lt;&lt; endl;  
    } cout << "<br/>\n"; cout << "</body>\n"; cout << "</html>\n"; return 0; }

    Passing Radio Button Data to CGI Program

    Radio Buttons are used when only one option is required to be selected.

    Here is example HTML code for a form with two radio button −

    <form action = "/cgi-bin/cpp_radiobutton.cgi" method = "post" target = "_blank">
       <input type = "radio" name = "subject" value = "maths" checked = "checked"/> Maths 
       <input type = "radio" name = "subject" value = "physics" /> Physics
       <input type = "submit" value = "Select Subject" />
    </form>

    The result of this code is the following form − Maths  Physics 

    Below is C++ program, which will generate cpp_radiobutton.cgi script to handle input given by web browser through radio buttons.

    #include <iostream>
    #include <vector>  
    #include <string>  
    #include <stdio.h>  
    #include <stdlib.h> 
    
    #include <cgicc/CgiDefs.h> 
    #include <cgicc/Cgicc.h> 
    #include <cgicc/HTTPHTMLHeader.h> 
    #include <cgicc/HTMLClasses.h> 
    
    using namespace std;
    using namespace cgicc;
    
    int main () {
       Cgicc formData;
      
       cout << "Content-type:text/html\r\n\r\n";
       cout << "<html>\n";
       cout << "<head>\n";
       cout << "<title>Radio Button Data to CGI</title>\n";
       cout << "</head>\n";
       cout << "<body>\n";
    
       form_iterator fi = formData.getElement("subject");  
       if( !fi->isEmpty() && fi != (*formData).end()) {  
    
      cout &lt;&lt; "Radio box selected: " &lt;&lt; **fi &lt;&lt; endl;  
    } cout << "<br/>\n"; cout << "</body>\n"; cout << "</html>\n"; return 0; }

    Passing Text Area Data to CGI Program

    TEXTAREA element is used when multiline text has to be passed to the CGI Program.

    Here is example HTML code for a form with a TEXTAREA box −

    <form action = "/cgi-bin/cpp_textarea.cgi" method = "post" target = "_blank">
       <textarea name = "textcontent" cols = "40" rows = "4">
    
      Type your text here...
    </textarea> <input type = "submit" value = "Submit" /> </form>

    The result of this code is the following form −

    Below is C++ program, which will generate cpp_textarea.cgi script to handle input given by web browser through text area.

    #include <iostream>
    #include <vector>  
    #include <string>  
    #include <stdio.h>  
    #include <stdlib.h> 
    
    #include <cgicc/CgiDefs.h> 
    #include <cgicc/Cgicc.h> 
    #include <cgicc/HTTPHTMLHeader.h> 
    #include <cgicc/HTMLClasses.h> 
    
    using namespace std;
    using namespace cgicc;
    
    int main () {
       Cgicc formData;
      
       cout << "Content-type:text/html\r\n\r\n";
       cout << "<html>\n";
       cout << "<head>\n";
       cout << "<title>Text Area Data to CGI</title>\n";
       cout << "</head>\n";
       cout << "<body>\n";
    
       form_iterator fi = formData.getElement("textcontent");  
       if( !fi->isEmpty() && fi != (*formData).end()) {  
    
      cout &lt;&lt; "Text Content: " &lt;&lt; **fi &lt;&lt; endl;  
    } else {
      cout &lt;&lt; "No text entered" &lt;&lt; endl;  
    } cout << "<br/>\n"; cout << "</body>\n"; cout << "</html>\n"; return 0; }

    Passing Drop down Box Data to CGI Program

    Drop down Box is used when we have many options available but only one or two will be selected.

    Here is example HTML code for a form with one drop down box −

    <form action = "/cgi-bin/cpp_dropdown.cgi" method = "post" target = "_blank">
       <select name = "dropdown">
    
      &lt;option value = "Maths" selected&gt;Maths&lt;/option&gt;
      &lt;option value = "Physics"&gt;Physics&lt;/option&gt;
    </select> <input type = "submit" value = "Submit"/> </form>

    The result of this code is the following form − Maths Physics  

    Below is C++ program, which will generate cpp_dropdown.cgi script to handle input given by web browser through drop down box.

    #include <iostream>
    #include <vector>  
    #include <string>  
    #include <stdio.h>  
    #include <stdlib.h> 
    
    #include <cgicc/CgiDefs.h> 
    #include <cgicc/Cgicc.h> 
    #include <cgicc/HTTPHTMLHeader.h> 
    #include <cgicc/HTMLClasses.h> 
    
    using namespace std;
    using namespace cgicc;
    
    int main () {
       Cgicc formData;
      
       cout << "Content-type:text/html\r\n\r\n";
       cout << "<html>\n";
       cout << "<head>\n";
       cout << "<title>Drop Down Box Data to CGI</title>\n";
       cout << "</head>\n";
       cout << "<body>\n";
    
       form_iterator fi = formData.getElement("dropdown");  
       if( !fi->isEmpty() && fi != (*formData).end()) {  
    
      cout &lt;&lt; "Value Selected: " &lt;&lt; **fi &lt;&lt; endl;  
    } cout << "<br/>\n"; cout << "</body>\n"; cout << "</html>\n"; return 0; }

    Using Cookies in CGI

    HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. For example one user registration ends after completing many pages. But how to maintain user’s session information across all the web pages.

    In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.

    How It Works

    Your server sends some data to the visitor’s browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor’s hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored.

    Cookies are a plain text data record of 5 variable-length fields −

    • Expires − This shows date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
    • Domain − This shows domain name of your site.
    • Path − This shows path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
    • Secure − If this field contains the word “secure” then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
    • Name = Value − Cookies are set and retrieved in the form of key and value pairs.

    Setting up Cookies

    It is very easy to send cookies to browser. These cookies will be sent along with HTTP Header before the Content-type filed. Assuming you want to set UserID and Password as cookies. So cookies setting will be done as follows

    #include <iostream>
    using namespace std;
    
    int main () {
       cout << "Set-Cookie:UserID = XYZ;\r\n";
       cout << "Set-Cookie:Password = XYZ123;\r\n";
       cout << "Set-Cookie:Domain = www.tutorialspoint.com;\r\n";
       cout << "Set-Cookie:Path = /perl;\n";
       cout << "Content-type:text/html\r\n\r\n";
    
       cout << "<html>\n";
       cout << "<head>\n";
       cout << "<title>Cookies in CGI</title>\n";
       cout << "</head>\n";
       cout << "<body>\n";
    
       cout << "Setting cookies" << endl;  
      
       cout << "<br/>\n";
       cout << "</body>\n";
       cout << "</html>\n";
       
       return 0;
    }

    From this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies.

    Here, it is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line “Content-type:text/html\r\n\r\n.

    Compile above program to produce setcookies.cgi, and try to set cookies using following link. It will set four cookies at your computer −

    /cgi-bin/setcookies.cgi

    Retrieving Cookies

    It is easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form.

    key1 = value1; key2 = value2; key3 = value3....
    

    Here is an example of how to retrieve cookies.

    #include <iostream>
    #include <vector>  
    #include <string>  
    #include <stdio.h>  
    #include <stdlib.h> 
    
    #include <cgicc/CgiDefs.h> 
    #include <cgicc/Cgicc.h> 
    #include <cgicc/HTTPHTMLHeader.h> 
    #include <cgicc/HTMLClasses.h>
    
    using namespace std;
    using namespace cgicc;
    
    int main () {
       Cgicc cgi;
       const_cookie_iterator cci;
    
       cout << "Content-type:text/html\r\n\r\n";
       cout << "<html>\n";
       cout << "<head>\n";
       cout << "<title>Cookies in CGI</title>\n";
       cout << "</head>\n";
       cout << "<body>\n";
       cout << "<table border = \"0\" cellspacing = \"2\">";
       
       // get environment variables
       const CgiEnvironment& env = cgi.getEnvironment();
    
       for( cci = env.getCookieList().begin();
       cci != env.getCookieList().end(); 
       ++cci ) {
    
      cout &lt;&lt; "&lt;tr&gt;&lt;td&gt;" &lt;&lt; cci-&gt;getName() &lt;&lt; "&lt;/td&gt;&lt;td&gt;";
      cout &lt;&lt; cci-&gt;getValue();                                 
      cout &lt;&lt; "&lt;/td&gt;&lt;/tr&gt;\n";
    } cout << "</table><\n"; cout << "<br/>\n"; cout << "</body>\n"; cout << "</html>\n"; return 0; }

    Now, compile above program to produce getcookies.cgi, and try to get a list of all the cookies available at your computer −

    This will produce a list of all the four cookies set in previous section and all other cookies set in your computer −

    UserID XYZ 
    Password XYZ123 
    Domain www.tutorialspoint.com 
    Path /perl 
    

    File Upload Example

    To upload a file the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type will create a “Browse” button.

    <html>
       <body>
    
      &lt;form enctype = "multipart/form-data" action = "/cgi-bin/cpp_uploadfile.cgi"
         method = "post"&gt;
         &lt;p&gt;File: &lt;input type = "file" name = "userfile" /&gt;&lt;/p&gt;
         &lt;p&gt;&lt;input type = "submit" value = "Upload" /&gt;&lt;/p&gt;
      &lt;/form&gt;
    </body> </html>

    The result of this code is the following form −

    File: 

    Note − Above example has been disabled intentionally to stop people uploading files on our server. But you can try above code with your server.

    Here is the script cpp_uploadfile.cpp to handle file upload −

    #include <iostream>
    #include <vector>  
    #include <string>  
    #include <stdio.h>  
    #include <stdlib.h> 
    
    #include <cgicc/CgiDefs.h> 
    #include <cgicc/Cgicc.h> 
    #include <cgicc/HTTPHTMLHeader.h> 
    #include <cgicc/HTMLClasses.h>
    
    using namespace std;
    using namespace cgicc;
    
    int main () {
       Cgicc cgi;
    
       cout << "Content-type:text/html\r\n\r\n";
       cout << "<html>\n";
       cout << "<head>\n";
       cout << "<title>File Upload in CGI</title>\n";
       cout << "</head>\n";
       cout << "<body>\n";
    
       // get list of files to be uploaded
       const_file_iterator file = cgi.getFile("userfile");
       if(file != cgi.getFiles().end()) {
    
      // send data type at cout.
      cout &lt;&lt; HTTPContentHeader(file-&gt;getDataType());
      // write content at cout.
      file-&gt;writeToStream(cout);
    } cout << "<File uploaded successfully>\n"; cout << "</body>\n"; cout << "</html>\n"; return 0; }

    The above example is for writing content at cout stream but you can open your file stream and save the content of uploaded file in a file at desired location.

  • Write a Program for Finding the Roots of a Quadratic Equation

    C++// C++ program to find // Roots of a quadratic equation #include <iostream> #include <math.h> using namespace std; // Prints roots of quadratic equation ax*2 + bx + c void findRoots(int a, int b, int c) { // If a is 0, then equation is not quadratic if (a == 0) { cout << "Invalid"; return; } // Formulae to calculate D int d = b * b - 4 * a * c; // Formulae to calculate // square root of D double sqrt_val = sqrt(abs(d)); // Conditons for checking root if (d > 0) { cout << "Roots are real and different \n"; cout << (double)(-b + sqrt_val) / (2 * a) << "\n" << (double)(-b - sqrt_val) / (2 * a); } else if (d == 0) { cout << "Roots are real and same \n"; cout << -(double)b / (2 * a); } else { cout << "Roots are complex \n"; cout << -(double)b / (2 * a) << " + i" << sqrt_val / (2 * a) << "\n" << -(double)b / (2 * a) << " - i" << sqrt_val / (2 * a); } } int main() { int a = 1, b = 4, c = 4; findRoots(a, b, c); return 0; }

    Output

    Roots are real and same 
    -2
  • Write a Program to Calculate the Lowest Common Multiple (LCM) of Two Numbers

    C++// C++ program to // Find LCM of two numbers #include <iostream> using namespace std; long long gcd(long long int a, long long int b) { if (b == 0) return a; return gcd(b, a % b); } // Function to return LCM of two numbers long long lcm(int a, int b) { long long result = (a / gcd(a, b)) * b; return result; } int main() { int a = 24, b = 13; cout << "LCM : " << lcm(a, b); return 0; }

    Output

    LCM : 312
  •  Write a Program to Check Palindrome

    C++// C++ program to check if a // number is Palindrome or not #include <iostream> using namespace std; // Function to check Palindrome bool checkPalindrome(int n) { int ans = 0; int temp = n; while (temp != 0) { ans = (ans * 10) + (temp % 10); temp = temp / 10; } return (ans == n); } int main() { int n = 12321; if (checkPalindrome(n) == 1) { cout << "Yes\n"; } else { cout << "No\n"; } return 0; }

    Output

    Yes
  • Write a Program to Calculate the Greatest Common Divisor of Two Numbers

    C++// C++ program to find // GCD of two numbers #include <iostream> using namespace std; // Function to return gcd of a and b int gcd(int a, int b) { int result = min(a, b); while (result > 0) { if (a % result == 0 && b % result == 0) { break; } result--; } return result; } int main() { int a = 54, b = 33; cout << "GCD: " << gcd(a, b); return 0; }

    Output

    GCD: 3
  • Write a Program to Find the Nth Term of the Fibonacci Series

    C++// C++ Program to Find the // Nth Term of the Fibonacci Series #include <iostream> using namespace std; int fib(int n) { int first = 0, second = 1, ans; if (n == 0) return first; for (int i = 2; i <= n; i++) { ans = first + second; first = second; second = ans; } return ans; } int main() { int n = 13; cout << fib(n); return 0; }

    Output

    233
  • Multithreading

    Multithreading is a specialized form of multitasking and a multitasking is the feature that allows your computer to run two or more programs concurrently. In general, there are two types of multitasking: process-based and thread-based.

    Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program.

    A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

    Before C++ 11, there is no built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature.

    This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C++ program using POSIX. POSIX Threads, or Pthreads provides API which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris.

    Creating Threads

    The following routine is used to create a POSIX thread −

    #include <pthread.h>
    pthread_create (thread, attr, start_routine, arg) 
    

    Here, pthread_create creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code. Here is the description of the parameters −

    Sr.NoParameter & Description
    1threadAn opaque, unique identifier for the new thread returned by the subroutine.
    2attrAn opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object, or NULL for the default values.
    3start_routineThe C++ routine that the thread will execute once it is created.
    4argA single argument that may be passed to start_routine. It must be passed by reference as a pointer cast of type void. NULL may be used if no argument is to be passed.

    The maximum number of threads that may be created by a process is implementation dependent. Once created, threads are peers, and may create other threads. There is no implied hierarchy or dependency between threads.

    Terminating Threads

    There is following routine which we use to terminate a POSIX thread −

    #include <pthread.h>
    pthread_exit (status) 
    

    Here pthread_exit is used to explicitly exit a thread. Typically, the pthread_exit() routine is called after a thread has completed its work and is no longer required to exist.

    If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes.

    Example

    This simple example code creates 5 threads with the pthread_create() routine. Each thread prints a “Hello World!” message, and then terminates with a call to pthread_exit().

    #include <iostream>
    #include <cstdlib>
    #include <pthread.h>
    
    using namespace std;
    
    #define NUM_THREADS 5
    
    void *PrintHello(void *threadid) {
       long tid;
       tid = (long)threadid;
       cout << "Hello World! Thread ID, " << tid << endl;
       pthread_exit(NULL);
    }
    
    int main () {
       pthread_t threads[NUM_THREADS];
       int rc;
       int i;
       
       for( i = 0; i < NUM_THREADS; i++ ) {
    
      cout &lt;&lt; "main() : creating thread, " &lt;&lt; i &lt;&lt; endl;
      rc = pthread_create(&amp;threads&#91;i], NULL, PrintHello, (void *)i);
      
      if (rc) {
         cout &lt;&lt; "Error:unable to create thread," &lt;&lt; rc &lt;&lt; endl;
         exit(-1);
      }
    } pthread_exit(NULL); }

    Compile the following program using -lpthread library as follows −

    $gcc test.cpp -lpthread
    

    Now, execute your program which gives the following output −

    main() : creating thread, 0
    main() : creating thread, 1
    main() : creating thread, 2
    main() : creating thread, 3
    main() : creating thread, 4
    Hello World! Thread ID, 0
    Hello World! Thread ID, 1
    Hello World! Thread ID, 2
    Hello World! Thread ID, 3
    Hello World! Thread ID, 4


    Passing Arguments to Threads

    This example shows how to pass multiple arguments via a structure. You can pass any data type in a thread callback because it points to void as explained in the following example −

    #include <iostream>
    #include <cstdlib>
    #include <pthread.h>
    
    using namespace std;
    
    #define NUM_THREADS 5
    
    struct thread_data {
       int  thread_id;
       char *message;
    };
    
    void *PrintHello(void *threadarg) {
       struct thread_data *my_data;
       my_data = (struct thread_data *) threadarg;
    
       cout << "Thread ID : " << my_data->thread_id ;
       cout << " Message : " << my_data->message << endl;
    
       pthread_exit(NULL);
    }
    
    int main () {
       pthread_t threads[NUM_THREADS];
       struct thread_data td[NUM_THREADS];
       int rc;
       int i;
    
       for( i = 0; i < NUM_THREADS; i++ ) {
    
      cout &lt;&lt;"main() : creating thread, " &lt;&lt; i &lt;&lt; endl;
      td&#91;i].thread_id = i;
      td&#91;i].message = "This is message";
      rc = pthread_create(&amp;threads&#91;i], NULL, PrintHello, (void *)&amp;td&#91;i]);
      
      if (rc) {
         cout &lt;&lt; "Error:unable to create thread," &lt;&lt; rc &lt;&lt; endl;
         exit(-1);
      }
    } pthread_exit(NULL); }

    When the above code is compiled and executed, it produces the following result −

    main() : creating thread, 0
    main() : creating thread, 1
    main() : creating thread, 2
    main() : creating thread, 3
    main() : creating thread, 4
    Thread ID : 3 Message : This is message
    Thread ID : 2 Message : This is message
    Thread ID : 0 Message : This is message
    Thread ID : 1 Message : This is message
    Thread ID : 4 Message : This is message
    

    Joining and Detaching Threads

    There are following two routines which we can use to join or detach threads −

    pthread_join (threadid, status) 
    pthread_detach (threadid) 
    

    The pthread_join() subroutine blocks the calling thread until the specified ‘threadid’ thread terminates. When a thread is created, one of its attributes defines whether it is joinable or detached. Only threads that are created as joinable can be joined. If a thread is created as detached, it can never be joined.

    This example demonstrates how to wait for thread completions by using the Pthread join routine.

    #include <iostream>
    #include <cstdlib>
    #include <pthread.h>
    #include <unistd.h>
    
    using namespace std;
    
    #define NUM_THREADS 5
    
    void *wait(void *t) {
       int i;
       long tid;
    
       tid = (long)t;
    
       sleep(1);
       cout << "Sleeping in thread " << endl;
       cout << "Thread with id : " << tid << "  ...exiting " << endl;
       pthread_exit(NULL);
    }
    
    int main () {
       int rc;
       int i;
       pthread_t threads[NUM_THREADS];
       pthread_attr_t attr;
       void *status;
    
       // Initialize and set thread joinable
       pthread_attr_init(&attr);
       pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    
       for( i = 0; i < NUM_THREADS; i++ ) {
    
      cout &lt;&lt; "main() : creating thread, " &lt;&lt; i &lt;&lt; endl;
      rc = pthread_create(&amp;threads&#91;i], &amp;attr, wait, (void *)i );
      if (rc) {
         cout &lt;&lt; "Error:unable to create thread," &lt;&lt; rc &lt;&lt; endl;
         exit(-1);
      }
    } // free attribute and wait for the other threads pthread_attr_destroy(&attr); for( i = 0; i < NUM_THREADS; i++ ) {
      rc = pthread_join(threads&#91;i], &amp;status);
      if (rc) {
         cout &lt;&lt; "Error:unable to join," &lt;&lt; rc &lt;&lt; endl;
         exit(-1);
      }
      cout &lt;&lt; "Main: completed thread id :" &lt;&lt; i ;
      cout &lt;&lt; "  exiting with status :" &lt;&lt; status &lt;&lt; endl;
    } cout << "Main: program exiting." << endl; pthread_exit(NULL); }

    When the above code is compiled and executed, it produces the following result −

    main() : creating thread, 0
    main() : creating thread, 1
    main() : creating thread, 2
    main() : creating thread, 3
    main() : creating thread, 4
    Sleeping in thread
    Thread with id : 0 .... exiting
    Sleeping in thread
    Thread with id : 1 .... exiting
    Sleeping in thread
    Thread with id : 2 .... exiting
    Sleeping in thread
    Thread with id : 3 .... exiting
    Sleeping in thread
    Thread with id : 4 .... exiting
    Main: completed thread id :0  exiting with status :0
    Main: completed thread id :1  exiting with status :0
    Main: completed thread id :2  exiting with status :0
    Main: completed thread id :3  exiting with status :0
    Main: completed thread id :4  exiting with status :0
    Main: program exiting.
    
  • Write a Program to Check Whether a Number is an Armstrong Number or Not

    C++// C++ Program to check // if number is Armstrong // or not #include <iostream> using namespace std; int main() { int n = 153; int temp = n; int ans = 0; // function to calculate // the sum of individual digits while (n > 0) { int rem = n % 10; ans = (ans) + (rem * rem * rem); n = n / 10; } // condition to check if (temp == ans) { cout << ("Yes, it is Armstrong Number"); } else { cout << ("No, it is not an Armstrong Number"); } return 0; }

    Output

    Yes, it is Armstrong Number
  •  Write a Program to Check Palindrome

    C++// C++ program to check if a // number is Palindrome or not #include <iostream> using namespace std; // Function to check Palindrome bool checkPalindrome(int n) { int ans = 0; int temp = n; while (temp != 0) { ans = (ans * 10) + (temp % 10); temp = temp / 10; } return (ans == n); } int main() { int n = 12321; if (checkPalindrome(n) == 1) { cout << "Yes\n"; } else { cout << "No\n"; } return 0; }

    Output

    Yes
  • Signal Handling

    Signals are the interrupts delivered to a process by the operating system which can terminate a program prematurely. You can generate interrupts by pressing Ctrl+C on a UNIX, LINUX, Mac OS X or Windows system.

    There are signals which can not be caught by the program but there is a following list of signals which you can catch in your program and can take appropriate actions based on the signal. These signals are defined in C++ header file <csignal>.

    Sr.NoSignal & Description
    1SIGABRTAbnormal termination of the program, such as a call to abort.
    2SIGFPEAn erroneous arithmetic operation, such as a divide by zero or an operation resulting in overflow.
    3SIGILLDetection of an illegal instruction.
    4SIGINTReceipt of an interactive attention signal.
    5SIGSEGVAn invalid access to storage.
    6SIGTERMA termination request sent to the program.

    The signal() Function

    C++ signal-handling library provides function signal to trap unexpected events. Following is the syntax of the signal() function −

    void (*signal (int sig, void (*func)(int)))(int); 
    

    Keeping it simple, this function receives two arguments: first argument as an integer which represents signal number and second argument as a pointer to the signal-handling function.

    Let us write a simple C++ program where we will catch SIGINT signal using signal() function. Whatever signal you want to catch in your program, you must register that signal using signal function and associate it with a signal handler. Examine the following example −

    #include <iostream>
    #include <csignal>
    
    using namespace std;
    
    void signalHandler( int signum ) {
       cout << "Interrupt signal (" << signum << ") received.\n";
    
       // cleanup and close up stuff here  
       // terminate program  
    
       exit(signum);  
    }
    
    int main () {
       // register signal SIGINT and signal handler  
       signal(SIGINT, signalHandler);  
    
       while(1) {
    
      cout &lt;&lt; "Going to sleep...." &lt;&lt; endl;
      sleep(1);
    } return 0; }

    When the above code is compiled and executed, it produces the following result −

    Going to sleep....
    Going to sleep....
    Going to sleep....
    

    Now, press Ctrl+c to interrupt the program and you will see that your program will catch the signal and would come out by printing something as follows −

    Going to sleep....
    Going to sleep....
    Going to sleep....
    Interrupt signal (2) received.
    

    The raise() Function

    You can generate signals by function raise(), which takes an integer signal number as an argument and has the following syntax.

    int raise (signal sig);
    

    Here, sig is the signal number to send any of the signals: SIGINT, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM, SIGHUP. Following is the example where we raise a signal internally using raise() function as follows −

    #include <iostream>
    #include <csignal>
    
    using namespace std;
    
    void signalHandler( int signum ) {
       cout << "Interrupt signal (" << signum << ") received.\n";
    
       // cleanup and close up stuff here  
       // terminate program  
    
       exit(signum);  
    }
    
    int main () {
       int i = 0;
       // register signal SIGINT and signal handler  
       signal(SIGINT, signalHandler);  
    
       while(++i) {
    
      cout &lt;&lt; "Going to sleep...." &lt;&lt; endl;
      if( i == 3 ) {
         raise( SIGINT);
      }
      sleep(1);
    } return 0; }

    When the above code is compiled and executed, it produces the following result and would come out automatically −

    Going to sleep....
    Going to sleep....
    Going to sleep....
    Interrupt signal (2) received.