boa 读取txt文件中温湿度以及时间值

viewdata.c

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define DATAFILE "/var/www/cgi-bin/data.txt"
int main(void)
{
    FILE *f = fopen(DATAFILE,"r");
    char ch;
    char wendu[10];
    char shidu[10];
    char stime[20];
    int i=0;
    int j=0;
    int k=0;
    int flag=0;
    if(f == NULL) //判断打开文件是否成功
    {
        printf("Content-type:text/html;charset=gb2312\n\n");
        printf("<TITLE>错误</TITLE>");
        printf("<p><EM>意外错误,无法打开文件</EM>");
    }
    else//打开文件成功,开始输出网页
    {
        printf("Content-type:text/html\n\n");
        printf("<html>\n");
        printf("<head><title>viewdata</title></head>\n");
        printf("<body>\n");
        printf("温度:");
        while((ch=getc(f))!='\n') //判断是否到了一行的末尾
        {
            if(ch!=' '&&flag==0) //flag=0表示正在读温度
            {
                wendu=ch;
                i++;
            }
            else if(flag==0)
            {
                wendu='\0';
                flag=1;
                printf("%s",wendu);
                printf("<br>湿度:");
                continue;
            }
            else if(ch!=' '&&flag==1) //flag=1表示正在读湿度
            {
                shidu[j]=ch;
                j++;
            }
            else if(flag==1)
            {
                shidu[j]='\0';
                flag=2;    //flag=2表示读取时间
                printf("%s<br>时间:",shidu);
                continue;
            }
            else
            {
                stime[k]=ch;
                k++;
            }
        }
        stime[k]='\0';
        printf("%s",stime);
        printf("</body>\n");
        printf("</html>");
        fclose(f);
    }
    return 0;
}
data.txt内容如下:
37.3 28.5 14:59:01
37.3 28.5 14:59:02
37.3 28.5 14:59:03
37.3 28.5 14:59:04
37.3 28.5 14:59:05
37.3 28.5 14:59:06
37.3 28.5 14:59:07
37.3 28.5 14:59:08
37.3 28.5 14:59:09
37.3 28.5 14:59:10
//gcc -o viewdata.cgi viewdata.c     生成cgi程序
//然后在网页中输入   http://ip地址/viewdata.cgi
//运行结果如下:
温度:37.3
湿度:28.5
时间:14:59:01

 

posted @ 2020-07-03 20:21  前方路wx  阅读(225)  评论(0编辑  收藏  举报