[net.sources] C Comment Nesting Checker

toma (12/06/82)

	I too have been burned by c comments eating lines of code.  To
retaliate, I hacked out the following program this afternoon.
Judging by the extensive commentary, I thought that this might come in
handy for other unfortunates like myself...

	It complains about successive "begin comment" fields (/*) or end
comment fields that do not follow a begin comment field.  If no input
filenames are specified, it reads from the standard input.

			Tom Anderson
			John Fluke Mfg. Co., Inc.
			Everett, Washington

p.s.	Sorry if this is a duplicate - my original submission didn't
seem to make it past our ivory towers.

/*	Title:		cnest

	Purpose:	To find and report all nested or unclosed comments
			in a c source file.

	Author:		Tom Anderson

	Usage:		cnest <filename1> <filename2> ...

	History:	December 3, 1982	creation date
*/

#include <stdio.h>

#define TRUE 1
#define FALSE 0

main(argc,argv)
unsigned int argc ;
char *argv[] ;

{
    char c ;
    char prev_char;
    unsigned char in_comment;
    unsigned int line_number;
    unsigned int file_index;
    char status;
    FILE *chk_file;

    status = 0;
    file_index = 1;

    do {
	line_number = 1;
	in_comment = FALSE;
	prev_char = ' ';
	if (argc == 1)
	    chk_file = stdin;
	else
	{
	    if ((chk_file = fopen(argv[file_index],"r")) == (FILE *) NULL)
	    {
		fprintf(stderr,"%s: Can't access %s",argv[0],argv[file_index]);
		status = 2;
		continue;
	    }
	}

	while ( ( c = fgetc(chk_file) ) !=  EOF )
	{
	    switch (c)
	    {
		case '\n':
		    line_number++;
		    break;
		case '/':
		    if (prev_char == '*')
		    {
			if (! in_comment) {
			    if (argc >= 2)
				fprintf(stderr,
				"%s: Line %d: Comment close without begin\n",
				argv[file_index],line_number);
			    else
				fprintf(stderr,
				"Line %d: Comment close without begin\n",
				line_number);
			    status = 1;
			}
			in_comment = FALSE;
		    }
		    break;
		case '*':
		    if (prev_char == '/')
		    {
			if (in_comment) {
			    if (argc >= 2)
				fprintf(stderr,
				"%s: Line %d: Consecutive comment begins\n",
				argv[file_index],line_number);
			    else
				fprintf(stderr,
				"Line %d: Consecutive comment begins\n",
				line_number);
			    status = 1;
			}
			in_comment = TRUE;
		    }
		    break;
		default:
		    break;
	    }
	    prev_char = c;
	}
	fclose(chk_file);
    } while (++file_index < argc);
    exit (status);
}