Search code examples
htmlcapacheserver-side

Using a C CGI to serve HTML templates/forms


Is it possible to call / display an HTML template in a C (or C++) CGI script (without embedding the raw HTML code into the script).

For example....

"http://localhost/cgi-bin/c-program.cgi" will serve "/var/www/cgi-bin/hello-world.html" in the browser as though it were a stand alone webpage. With the exception of the URL, the user would not know the difference.

Edited because I do not wish to be flagged as 'vague':

/* C-PROGRAM.CGI - displays parsed html */
#include <stdio.h>
#include <stdlib.h>

int main (void) {
    FILE *fp;
    fp = fopen ("/var/www/cgi-bin/hello-world.html", "r")
    if (fp == NULL) {
         printf ("File not available, errno = %d\n", errno);
         return 1;
    }

    // Display all of parsed hello-world.html in browser

    fclose (fp);
    return 0;
}

This snippet should give you a sense of what I want to achieve; how can I achieve it... if at all? The program would be executed via http://localhost/cgi-bin/c-program.cgi

My reading keeps leading me down the path of processing characters or lines of the HTML only...


Solution

  • If you want to run C scripts for html you must either do it though CGI-BIN (which you have figured out) or you must do it with your own Apache module. The latter has plenty of tutorials all over the web on how to do it.

    If you want to use cgi-bin in the style, program.cgi will simply use fopen on your html file and print the contents of the file out using printf.

    void print_file(FILE *f)
    {
        int c;
        if (f)
        {
            while ((c = getc(f)) != EOF)
                putchar(c);
            fclose(f);
        }
    }
    
    int main()
    {
        FILE *content = fopen ("/var/www/cgi-bin/hello-world.html", "r");
        FILE *header = fopen ("/var/www/cgi-bin/header.html", "r");
        FILE *footer = fopen ("/var/www/cgi-bin/footer.html", "r");
    
        printf("Content-Type: text/html \n\n");
        print_file(header);
        print_file(content);
        print_file(footer);
        return 0;
    }