| 1 | #include <stdio.h> |
| 2 | #include <string.h> |
| 3 | |
| 4 | |
| 5 | static int check_defines(const char **defs, int defcount, char *tdef) |
| 6 | { |
| 7 | int i, len; |
| 8 | |
| 9 | len = strlen(tdef); |
| 10 | for (i = 0; i < len; i++) |
| 11 | if (tdef[i] == ' ' || tdef[i] == '\r' || tdef[i] == '\n') break; |
| 12 | tdef[i] = 0; |
| 13 | |
| 14 | for (i = 0; i < defcount; i++) |
| 15 | { |
| 16 | if (strcmp(defs[i], tdef) == 0) |
| 17 | return 1; |
| 18 | } |
| 19 | |
| 20 | return 0; |
| 21 | } |
| 22 | |
| 23 | |
| 24 | static void do_counters(char *str) |
| 25 | { |
| 26 | static int counters[4] = { 1, 1, 1, 1 }; |
| 27 | char buff[1024]; |
| 28 | int counter; |
| 29 | char *s = str; |
| 30 | |
| 31 | while ((s = strstr(s, "@@"))) |
| 32 | { |
| 33 | if (s[2] < '0' || s[2] > '3') { s++; continue; } |
| 34 | |
| 35 | counter = s[2] - '0'; |
| 36 | snprintf(buff, sizeof(buff), "%i%s", counters[counter]++, s + 3); |
| 37 | strcpy(s, buff); |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | |
| 42 | int main(int argc, char *argv[]) |
| 43 | { |
| 44 | char buff[1024]; |
| 45 | FILE *fi, *fo; |
| 46 | int skip_mode = 0, ifdef_level = 0, line = 0; |
| 47 | |
| 48 | if (argc < 3) |
| 49 | { |
| 50 | printf("usage:\n%s <file_in> <file_out> [defines...]\n", argv[0]); |
| 51 | return 1; |
| 52 | } |
| 53 | |
| 54 | fi = fopen(argv[1], "r"); |
| 55 | if (fi == NULL) |
| 56 | { |
| 57 | printf("failed to open: %s\n", argv[1]); |
| 58 | return 2; |
| 59 | } |
| 60 | |
| 61 | fo = fopen(argv[2], "w"); |
| 62 | if (fo == NULL) |
| 63 | { |
| 64 | printf("failed to open: %s\n", argv[2]); |
| 65 | return 3; |
| 66 | } |
| 67 | |
| 68 | for (++line; !feof(fi); line++) |
| 69 | { |
| 70 | char *fgs; |
| 71 | |
| 72 | fgs = fgets(buff, sizeof(buff), fi); |
| 73 | if (fgs == NULL) break; |
| 74 | |
| 75 | if (buff[0] == '#') |
| 76 | { |
| 77 | /* control char */ |
| 78 | if (strncmp(buff, "#ifdef ", 7) == 0) |
| 79 | { |
| 80 | if (!check_defines((void *) &argv[3], argc-3, buff + 7)) skip_mode = 1; |
| 81 | ifdef_level++; |
| 82 | } |
| 83 | else if (strncmp(buff, "#ifndef ", 8) == 0) |
| 84 | { |
| 85 | if ( check_defines((void *) &argv[3], argc-3, buff + 7)) skip_mode = 1; |
| 86 | ifdef_level++; |
| 87 | } |
| 88 | else if (strncmp(buff, "#else", 5) == 0) |
| 89 | { |
| 90 | skip_mode ^= 1; |
| 91 | } |
| 92 | else if (strncmp(buff, "#endif", 6) == 0) |
| 93 | { |
| 94 | ifdef_level--; |
| 95 | if (ifdef_level == 0) skip_mode = 0; |
| 96 | if (ifdef_level < 0) |
| 97 | { |
| 98 | printf("%i: warning: #endif without #ifdef, ignoring\n", line); |
| 99 | ifdef_level = 0; |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /* skip line */ |
| 104 | continue; |
| 105 | } |
| 106 | if (!skip_mode) |
| 107 | { |
| 108 | do_counters(buff); |
| 109 | fputs(buff, fo); |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | fclose(fi); |
| 114 | fclose(fo); |
| 115 | |
| 116 | return 0; |
| 117 | } |
| 118 | |