以前不知道在哪里好像见过,就想起来写这个程序了,但是写完以后发现 哎,一天写了这一点,太水了....哎........,关键是写的不好,先记下来,以后有机会再改!!!
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <assert.h>
#define ENDIF "#endif"
#define RN "\r\n"
char* parse_file(const char *buffer, const int size){
int length = 0;
char *tem = NULL;
char *file_start = buffer;
const char *file_ptr = buffer;
const char *file_end = buffer + size;
char *sq_ptr = NULL; //single quote '
char *dq_ptr = NULL; //double quote "
char *star_ptr = NULL; //star quote /*
char *slash_ptr = NULL; //slash quote //
assert(buffer);
assert(size>0);
while (file_ptr < file_end)
{
switch (*file_ptr)
{
case '\"': //handle double quote
if (sq_ptr || star_ptr || slash_ptr)
break;
tem = strstr(file_ptr + 1, "\"");
length = tem - file_ptr + 1;
file_ptr += length;
break;
case '\*':
if (sq_ptr || dq_ptr || slash_ptr)
break;
else if (star_ptr && *(file_ptr + 1) == '/'){
file_ptr += 2;
memset(star_ptr, ' ', file_ptr - star_ptr);
star_ptr = NULL;
}
else if (*(file_ptr - 1) == '/')
star_ptr = file_ptr - 1;
else
file_ptr = file_ptr;
break;
case '/':
if (sq_ptr || dq_ptr || star_ptr)
break;
else if (*(file_ptr + 1) == '/'){
tem = strstr(file_ptr, RN);
if (tem == NULL){
length = file_end - file_ptr;
memset(file_ptr, ' ', length);
file_ptr = file_end;
break;
}
length = tem - file_ptr + 1;
memset(file_ptr, ' ', length);
file_ptr = tem + 1;
}
else
file_ptr = file_ptr;
break;
case '\'':
if (star_ptr || dq_ptr || slash_ptr)
break;
else if (sq_ptr == NULL)
sq_ptr = file_ptr;
else{
length = file_ptr - sq_ptr;
if ((length == 3) && (*(sq_ptr + 1) == '\\' || *(sq_ptr + 1) == '//'));
file_ptr += length;
sq_ptr = NULL;
}
break;
case '#':
if (*(file_ptr + 1) == 'i' && *(file_ptr + 2) == 'f'){
tem = strstr(file_ptr, ENDIF);
length = tem - file_ptr + 6;
memset(file_ptr, ' ', length);
file_ptr += length;
}
default:
break;
}
file_ptr++;
}
return file_start;
}
int main(void){
char *buffer = NULL;
struct _stat st;
FILE *source_file = NULL;
const char *file_name = "source.cpp";
source_file = fopen(file_name, "rb+");
if (source_file == NULL)
return -1;
if (_stat(file_name, &st) == -1)
return -1;
buffer = (char *)malloc(sizeof(char)*(st.st_size + 1));
if (buffer == NULL)
return -1;
fread(buffer, st.st_size, 1, source_file);
buffer = parse_file(buffer, st.st_size);
*(buffer + st.st_size) = '\0';
printf("%s", buffer);
fclose(source_file);
return 1;
}