本方法适用于分离C语言风格的注释。
> gcc parse.c -o parse
> ./parse -s parse.c
源文件parse.c
- #include <stdio.h>
-
#include <string.h>
-
#define CODE_FILE "code_file.txt"
-
#define COMMENT_FILE "comment_file.txt"
-
-
void split(const char* filename)
-
{
-
FILE* fin = fopen(filename, "r");
-
FILE* fcode = fopen(CODE_FILE, "w");
-
FILE* fcomm = fopen(COMMENT_FILE, "w");
-
//测试数据
-
"123456测试数据";
-
/*这是测试数据*/
-
"````````````\"" "1111111111";
-
while (!feof(fin))
-
{
-
char c = fgetc(fin);
-
if (c == EOF) break;
-
-
if (c == '"' || c == '\'')
-
{
-
char t = c;
-
fputc(c, fcode);
-
while ((c = fgetc(fin)) != EOF && c != t)
-
{
-
fputc(c, fcode);
-
if (c == '\\')
-
{
-
if ((c = fgetc(fin)) != EOF)
-
fputc(c, fcode);
-
}
-
}
-
if (c == t) fputc(c, fcode);
-
else break;
-
}/***********************/
-
else if (c == '/')
-
{/*
-
-
换行测试
-
灭哈哈
-
*/
-
char c1 = fgetc(fin);
-
if (c1 == '*')
-
{
-
fprintf(fcomm, "@%d@%d@\n", ftell(fcode), 0);
-
fprintf(fcomm, "/*");
-
c1 = 0;
-
while (1)
-
{
-
while (c1 != '*' && c1 != EOF)
-
{
-
if (c1) fputc(c1, fcomm);
-
c1 = fgetc(fin);
-
}
-
if (c1 == EOF) break;
-
c1 = fgetc(fin);
-
if (c1 == '/' || c1 == EOF) break;
-
else fputc('*', fcomm);
-
}
-
fprintf(fcomm, "*/\n");
-
}
-
else if (c1 == '/')
-
{
-
fprintf(fcomm, "@%d@%d@\n", ftell(fcode), 1);
-
fprintf(fcomm, "//");
-
while ((c1 = fgetc(fin)) != EOF && c1 != '\n') fputc(c1, fcomm);
-
fprintf(fcomm, "\n");
-
}
-
else
-
{
-
fprintf(fcode, "%c%c", c, c1);
-
}
-
}
-
else
-
{/*飞雪
-
-
//
-
//测试
-
//
-
*/
-
fputc(c, fcode);
-
}
-
}
-
fclose(fcomm);
-
fclose(fcode);
-
fclose(fin);
-
}
-
//测试一下
-
void merge(const char* filename)
-
{
-
FILE* fout = fopen(filename, "w");
-
FILE* fcode = fopen(CODE_FILE, "r");
-
FILE* fcomm = fopen(COMMENT_FILE, "r");
-
-
char temp[256] = {0};
-
while (!feof(fcomm))
-
{
-
int pos, type;
-
char c;
-
if (fscanf(fcomm, "@%d@%d@\n", &pos, &type) == EOF) break;
-
while (ftell(fcode) != pos)
-
{
-
c = fgetc(fcode);
-
fputc(c, fout);
-
}
-
if (type == 1)
-
{
-
while ((c = getc(fcomm)) != '\n') fputc(c, fout);
-
fputc('\n', fout);
-
}
-
else
-
{
-
char c = 0;
-
while (1)
-
{
-
while (c != '*' && c != EOF)
-
{
-
if (c) fputc(c, fout);
-
c = fgetc(fcomm);
-
}
-
if (c == EOF) break;
-
c = fgetc(fcomm);
-
if (c == '/' || c == EOF) break;
-
else fputc('*', fout);
-
}
-
fprintf(fout, "*/");
-
fgetc(fcomm);
-
}
-
}
-
while (!feof(fcode))
-
{
-
char c = fgetc(fcode);
-
if (c == EOF) break;
-
fputc(c, fout);
-
}
-
fclose(fcomm);
-
fclose(fcode);
-
fclose(fout);
-
}
-
int main(int cnt, char* args[])
-
{
-
if (cnt != 3)
-
{
-
puts("usage:\n -s filename\n -m filename\n");
-
return 1;
-
}
-
if (args[1][0] == '-' && args[1][1] == 's')
-
{
-
split(args[2]);
-
}
-
else if (args[1][0] == '-' && args[1][1] == 'm')
-
{
-
merge(args[2]);
-
}
-
else
-
{
-
puts("usage:\n -s filename\n -m filename\n");
-
return 1;
-
}
-
return 0;
-
}
-
//测试数据
-
//"123456测试数据";
-
/*这是测试数据*/
转载自:http://www.cnblogs.com/chengxin1982/archive/2009/01/18/1377781.html
阅读(1865) | 评论(0) | 转发(0) |