/* ** C_LINES.C - Count lines of code in a C program. ** ** NOTES: ** ** 1. Skips both C and C++ style comments ** 2. Counts all lines of conditional code. ** 3. Line length limited to 256 characters. ** 4. To expand command line arguments with wildcards, ** TC/TC++/BC++ - Link in WILDARGS.OBJ. ** MSC/QC - Link in SETARGV.OBJ. ** ZTC/C++ - Link in _MAINx.OBJ, where 'x' is the memory model. ** Watcom C/C++ - Compile & link with WILDARGV.C ** ** public domain by Bob Stout */ #include #include #define NUL '\0' main(int argc, char *argv[]) { FILE *fp; while (--argc) { char line[256]; int lines = 0; if (NULL == (fp = fopen(*++argv, "r"))) { printf("Can't open %s - skipping\n", *argv); continue; } while (!feof(fp)) { char *p; if (NULL != fgets(line, 256, fp)) { /* ** First, strip leading spaces */ for (p = line; ' ' == *p; ++p) ; TEST: switch (*p) { case NUL: /* Don't count blank lines */ case '\n': continue; default: /* Ignore C++ comments */ if (0 == strncmp("//", p, 2)) continue; /* Look for C comments */ if (0 == strncmp("/*", p, 2)) { SKIP: while (NULL == (p = strstr(line, "*/"))) { if (feof(fp)) { printf("%-12s: * Unterminated" " comment error *\n", strupr(*argv)); break; } fgets(line, 256, fp); } p += 2; goto TEST; } } ++lines; /* ** Look for embedded C comment starts, ** ignore them if within quotes. */ if (NULL != strstr(p, "/*")) { int quotes; *p = NUL; for (quotes = 0; NULL != (p = strrchr(line, '\"')); ++quotes) { if (p != line && NULL != strchr("'\\", *(p - 1))) { --quotes; } *p = NUL; } if (0 != (quotes & 1)) goto SKIP; } } } fclose(fp); printf("%-12s: %3d Lines\n", strupr(*argv), lines); } }