|
发表于 2004-3-25 21:11:41
|
显示全部楼层
刚才没什么事,就用C写了一个
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #define BUFSIZE 1024
- int codesize; /* 代码总大小 */
- int codebuf; /* 代码缓冲区大小 */
- char *code; /* 保存代码的缓冲区 */
- char *php; /* 保存PHP代码的缓冲区 */
- char *html; /* 保存HTML代码的缓冲区 */
- void getcode(int); /* 从文件获取代码 */
- void spcode(void); /* 把代码分开成PHP和HTML */
- int getLineNum(char *); /* 计算行数 */
- int
- main(int argc, char *argv[])
- {
- int fd;
- int i;
-
- /* 处理命令行参数,如果没有参数就读标准输入 */
- if(argc == 1)
- getcode(STDIN_FILENO);
- else
- for(i = 1; i < argc; ++i){
- if((fd = open(argv[i], O_RDONLY)) < 0){
- fprintf(stderr, "cannot open %s\n", argv[i]);
- continue;
- }
- getcode(fd);
- close(fd);
- }
- code[codesize] = '\0';
- /* 为了简单,所以分配的空间有点浪费 */
- php = (char *)malloc(codesize + 1);
- html = (char *)malloc(codesize + 1);
- spcode();
- printf("Total %d lines\n", getLineNum(code));
- printf("PHP: %d lines\n%s\n", getLineNum(php), php);
- printf("HTML: %d lines\n%s\n", getLineNum(html), html);
-
- free(code);
- free(php);
- free(html);
- exit(0);
- }
- void
- getcode(int fd)
- {
- char buf[BUFSIZE];
- int n;
-
- while((n = read(fd, buf, BUFSIZE)) > 0){
- if(codesize + n > codebuf){
- codebuf += BUFSIZE;
- code = (char *)realloc(code, codebuf + 1);
- }
- memcpy(code + codesize, buf, n);
- codesize += n;
- }
- if(n < 0){
- fprintf(stderr, "read error");
- exit(-1);
- }
- }
- void
- spcode(void)
- {
- /* h: HTML区指针; p: PHP区指针; c: code区指针; s: 搜索用指针 */
- char *h, *p, *c, *s;
- /* PHP代码起始和结束标签 */
- const char *label;
- const char * const begin = "<?php";
- const char * const end = "?>";
- int isphp = 0;
- h = html;
- p = php;
- c = code;
- label = begin;
- while(s = strstr(c, label)){
- if(isphp){
- memcpy(p, c, s - c);
- p += s - c;
- c = s + strlen(label);
- isphp = 0;
- label = begin;
- }else{
- memcpy(h, c, s - c);
- h += s - c;
- c = s + strlen(label);
- isphp = 1;
- label = end;
- }
- /* 如果PHP标签独占一行,不计算这一行 */
- if(*c == '\n')
- c++;
- }
- *p = '\0';
- strcpy(h, c);
- *(h + strlen(c)) = '\0';
- }
- int
- getLineNum(char *s)
- {
- int n = 0;
-
- /* 如果代码(C、P、H)为空,返回0,否则会返回1 */
- if(*s == '\0')
- return(0);
- while(*s)
- if(*s++ == '\n')
- n++;
- /* 如果代码最后不是\n,也应该算一行 */
- if(*(s - 1) != '\n')
- n++;
- return(n);
- }
复制代码 |
|