Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Counting lines of code without the comments and blank lines

Status
Not open for further replies.

Leibnitz

Programmer
Apr 6, 2001
393
CA
********************************************************************************************
If you've ever wanted to count the lines of your code without the comments and blank lines ,here is a piece of code that
i have wrote that will help you do it.
Code:
#include <stdio.h>
#include <string.h>
#include <direct.h>
#include <windows.h>

// checks if a certain file or directory exist
bool fExist( char* filepath )
{
    WIN32_FIND_DATA file;
    HANDLE hFile;
    if (( hFile = FindFirstFile( filepath,&file ))  
         == INVALID_HANDLE_VALUE )
    {
          return false;
    }
    return true;
}

// determin if a line is a blank line
bool isblankline( char *buff )
{
	for( int i = 0; buff[i] != 0; i++ )
	{
		if( buff[i] - ' ' > 0 )
			return false;
	}

	return true;
}

// determin if a line is a commentary
bool iscommentary( char *buff )
{
	for( int i = 0; buff[i] != 0; i++ )
	{
		if(( buff[i] - '/' == 0 ) && ( buff[i+1] - '/' == 0 ) || 
			( buff[i+1] - '*' == 0 ))
		{
			buff[i] = 0;
		}
	}

	if( isblankline( buff ))
		return true;

	return false;
}


void main()
{
	FILE *file;
	char *filename;
	char *buff;
	int lines = 0;
	
	// allocating memory for 'filename' and 'buff'
	try
	{
	    filename = ( char* )malloc( sizeof(char) * 200 );
	    buff = ( char* )malloc( sizeof(char) * 200 );

		if(!filename)
			throw -1;

		if(!buff)
			throw -2;
	}

	catch( int excpt )
	{
		switch( excpt )
		{
		case -1: fprintf( stderr, &quot;can't allocate memory for \&quot;filename\&quot; .\n&quot;);
			break;

		case -2: fprintf( stderr, &quot;can't allocate memory for \&quot;buff\&quot; .\n&quot;);
			break;
		}

		exit(1);
	}
	
	strcpy( filename, &quot;place your file name here&quot; ); // filename

	// this part is not strictly necessary but i have included anyway
	// it checks if the file exist
	if( !fExist( filename ))
	{
		fprintf( stderr, &quot;incorrect filename.\n&quot;);
		exit(1);
	}

	file = fopen( filename, &quot;r&quot; );

	if(!file)
	{
		fprintf( stderr, &quot;error while opening %s.\n&quot;, filename );
		exit(1);
	}

	while( fgets( buff, 100, file ) != NULL )
	{
		if( !isblankline( buff ) && !iscommentary( buff ))
		{
			lines++;
			//printf(&quot;%s&quot;,buff); // display the code without the blank lines and commentaries
		}
	}

	printf(&quot;There are %d lines in the file \&quot;%s\&quot;.\n&quot;, lines, filename );

	free( filename );
	free( buff );
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top