使用cgic库搭配ctemplate编写cgi程序

  这两天在写开发板上的cgi程序,使用的是C语言编写的我们知道用C语言来写cgi程序是件非常痛苦的事情,我们常常要把html代码写到c语言中进行输出,而且要写一些方法从环境变量中获取post或者get的值.然而我们使用cgic和ctemplate的话帮我们简化了不少的操作,并能把html和C语言分离开来.下面我们来看看怎么使用cgic和ctemplate来优雅的写个cgi程序,因为开发板在公司了,我这里就用pc的Wamp做cgi的服务器了。

  •  配置apache支持cgi。

首先我们先配置apache服务器让它支持cgi程序.找到httpd.conf文件确保

LoadModule cgi_module modules/mod_cgi.so

 这行前面的#去掉,接下来找到

Options Indexes FollowSymLinks

将其改为

Options Indexes FollowSymLinks Includes ExecCGI

找到

ScriptAlias /cgi-bin/ “D:/wamp/bin/apache/apache2.4.9/cgi-bin”

改为自己的路径,我的如下

ScriptAlias /cgi-bin/ "D:/wamp/www/cgi"

找到

<Directory "D:/wamp/bin/apache/apache2.4.9/cgi-bin">

改为自己的路径,并修改节下的内容,有的人报没有权限就是因为这里没改,我的如下

<Directory "D:/wamp/www/cgi">
    AllowOverride All
    Options All
    Require all granted
</Directory>

再找到

#AddHandler cgi-script .cgi

去掉前面的#,重启服务器,编写一个cgi程序放到www/cgi/下打开浏览器哦运行,没错的话可以看到输出了。

  •  用编写cgic和ctemplate编写cgi。

我们先从官网上下载cgic https://boutell.com/cgic/ 和 ctemplate http://libccgi.sourceforge.net/,将cgic和ctemplat解压缩出来

可以看到cgic和ctemplat内容非常少非常简洁,其实里面主要的用到文件也就是cgic.h cgic.c和ctemplat.h ctemplat.c而已我们把它们拷贝到新的目录以便工作

好了,我们开始编写一个基于cgic ctemplat的cgi fact.c了,这个fact.c文件我是为了方便从ctemplat的例子里面拷过来修改的,大家测试的话,也可以考过来用就好了。

fact.c

/* This demo prints out a table of factorials */

#include <stdio.h>
#include "ctemplate.h"
#include "cgic.h"              // cgic库的头文件
int
cgiMain(int argc, char **argv) {
    int n, f;
    char txt1[32], txt2[32];
    TMPL_varlist *mainlist = 0, *vl = 0;
    TMPL_loop  *loop;

    cgiHeaderContentType("text/html;charset=gbk");    
    
    loop = 0;
    f = 1;
    for (n = 1; n < 11; n++) {
        sprintf(txt1, "%d", n);
        sprintf(txt2, "%d", f *= n);
        vl = TMPL_add_var(0, "n", txt1, "nfact", txt2, 0);
        loop = TMPL_add_varlist(loop, vl);
    } 
    mainlist = TMPL_add_var(0, "title", "10 factorials", 0);
    mainlist = TMPL_add_loop(mainlist, "fact", loop);
    TMPL_write("fact.tmpl", 0, 0, mainlist, cgiOut,cgiOut); 
    TMPL_free_varlist(mainlist);
    return 0;
}

模板文件如下

fact.tmpl

<html>
<head>
<title><TMPL_var name = "title"></title>
</head>
<body>
<h1><TMPL_var name = "title"></h1>
<p>
<table border=1>
<tr>
<th align=right>n</th>
<th align=right>n!</th>
</tr>
<TMPL_LOOP name = "fact">
    <tr>
    <td align=right><TMPL_VAR name = "n"></td>
    <td align=right><TMPL_VAR name = "nfact"></td>
    </tr>
</TMPL_LOOP>
</table>
</body>
</html>

好了我接下来编译这个C文件gcc cgic.c ctemplate.c fact.c -o f.cgi生产f.cgi,我们把cgi文件和模板文件拷到www/cgi下面运行.

好了大功告成.

至于cgic和ctemplate的是使用大家可以到官网http://libccgi.sourceforge.net/doc.html查查,这里不做讨论了。

工程下载

 转载请注明出处:http://www.cnblogs.com/fyluyg/p/6444169.html

原文地址:https://www.cnblogs.com/fyluyg/p/6444169.html