Rabu, 02 Desember 2009

C++ Lines Counter

 Have you ever wanted to count the lines of your code in C or C++ without the commentaries and blank lines,well with this program you can do it. Please feel free to vote or to live some comments,it will be very appreciated! Jay Idoan


#include < stdio.h >
#include < string.h >
#include < direct.h >
#include < windows.h >



// checks if a certain file or directiry 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, "can't allocate memory for \"filename\" .\n");
break;

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

exit(1);
}

strcpy( filename, "place your file name here" ); // filename

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

file = fopen( filename, "r" );

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

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

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

free( filename );
free( buff );
}

0 komentar:

Posting Komentar