前言
本篇的内容完全可以使用C+11的原生字符串string R="(字符串)" 代替。
本次是第一版,以后会不断完善的,代码很简单,就是读文件。
将双引号前加转义,其他的字符需要加转义的还没想到,等编译报错的时候再修改代码。
本次测试的目的:将html文件转换为如下形式的代码:
#include <stdio.h>
int main()
{
printf("Content-type:text/html\n\n"); //这句一定要加上
printf("<html><body>");
printf("<font style=\"color:red; font-size:30px;\">Hello, CGI!</font><br/>");
printf("<a href=\"/index.html\">return index.html</a>");
printf("</body></html>");
return 0;
}
1 编写html测试文件:
lkmao@ubuntu:/big/web/boa/boa-0.94.13/src/arm_boa/cgi-bin$ vi skip.html
<html>
<body>
<a href="/index.html">return index.html</a>
</body>
</html>
~
2 编写转换工具:
lkmao@ubuntu:/big/web/boa/boa-0.94.13/src/arm_boa/cgi-bin$ vi tool.c
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
char buf[1024];
char new_buf[1024];
char new_name[100];
char new_str[2048];
int main(int argc,char *argv[])
{
int len;
FILE *p;
FILE *p2;
char *pr;
int i = 0;
int j = 0;
if(argc < 2){
printf("no file name\n");
return -1;
}
p = fopen(argv[1],"r");
if(p == NULL){
printf("fopen fail\n");
return -2;
}
sprintf(new_name,"%s.cgi.c",argv[1]);
unlink(new_name);
p2 = fopen(new_name,"w");
fputs("#include <stdio.h>\n",p2);
fputs("int main()\n",p2);
fputs("{\n",p2);
fputs(" printf(\"Content-type:text/html\\n\\n\");\n",p2);
while(1){
memset(buf,0,sizeof(buf));
pr = fgets(buf,1024,p);
if(pr == NULL){
break;
}
if(strlen(buf) < 2)continue;
buf[strlen(buf) - 1] = 0;
printf("buf = %s\n",buf);
memset(new_buf,0,sizeof(new_buf));
for(i = 0,j = 0;i < strlen(buf);i++){
if(buf[i] == '\"'){
new_buf[j] = '\\';
new_buf[j + 1] = '\"';
j += 2;
}else{
new_buf[j++] = buf[i];
}
}
memset(new_str,0,sizeof(new_str));
sprintf(new_str," printf(\"%s\");\n",new_buf);
fputs(new_str,p2);
}
fputs(" return 0;\n",p2);
fputs("}\n",p2);
printf("end\n");
fclose(p);
fclose(p2);
return 0;
}
3 编译测试
lkmao@ubuntu:/big/web/boa/boa-0.94.13/src/arm_boa/cgi-bin$ gcc tool.c
lkmao@ubuntu:/big/web/boa/boa-0.94.13/src/arm_boa/cgi-bin$ ./a.out skip.html
buf = <html>
buf = <body>
buf = <a href="/index.html">return index.html</a>
buf = </body>
buf = </html>
end
lkmao@ubuntu:/big/web/boa/boa-0.94.13/src/arm_boa/cgi-bin$ arm-linux-gnueabihf-gcc -o test.cgi skip.html.cgi.c
lkmao@ubuntu:/big/web/boa/boa-0.94.13/src/arm_boa/cgi-bin$ scp test.cgi root@192.168.0.3:/boa/cgi-bin/
test.cgi 100% 8292 8.1KB/s 00:00
lkmao@ubuntu:/big/web/boa/boa-0.94.13/src/arm_boa/cgi-bin$
在开发板上运行boa,并在windows浏览器登录网页
登录成功,点击超链接:如下所示,
成功跳转,说明,转换工具阶段性成功。