C语言设计一个基于CGI-BIN的网页计数器

描述:使用C语言设计一个基于CGI-BIN的网页计数器。
要求从多台计算机打开网页并刷新,计数器能正常累加;计数器的值需要能持久化存储,即不会每次都从初始值开始。即网页刷新一次,计数加一
在这里通过文件读写来实现持久化存储。

条件:安装配置好apache

实现
1.在/var/www/cgi-bin目录下新建count.c文件,输入以下代码

#include<stdio.h>
int main()
{
    
    

   printf("Content-type:text/html\n\n");
   printf("<html>\n");
   printf("<head><title>An html page from a cgi</title></head>\n");
   printf("<body bgcolor=\"#E6E6FA\"></body>\n");
   printf("</html>\n");
   fflush(stdout);
   FILE *fp = NULL;
   int num;
   fp = fopen("test.txt", "r");
   fscanf(fp,"%d",&num);
   fclose(fp);
   printf("A simple amount counter:\n");
   printf("%d",num);
   fp = fopen("test.txt", "w");
   num++;
   fprintf(fp, "%d",num);
   fclose(fp);
}

2.在同目录下新建test.txt文件,输入0作为计数初始值,设置文件属性
在这里插入图片描述

sudo chmod 666 test.txt

3.输入以下代码

sudo gcc -o count.cgi count.c

4.在浏览器中打开localhost/cgi-bin/count.cgi即可实现上述功能,刷新网页一次计数加1,关闭网页重新打开计数为上次结束前的计数结果+1,同ip下输入
localhost/cgi-bin/count.cgi都能使用该网页计数器

猜你喜欢

转载自blog.csdn.net/weixin_44925547/article/details/106320305