How many lines of source code will be mentioned in some books on Software Engineering. for example, projects with 1 million lines of code and 100,000 lines of code may adopt different management methods. so I want to know how many lines of code I have participated in. but when I asked my colleagues, I was not quite clear about it. It may look like hundreds of thousands or even millions of people. this is too inaccurate. so I thought of writing some code to calculate it.
In fact, the method is very simple. Just traverse all the source files and then calculate the number of lines of code in each source file. below is the detailed code.
Using system. IO; // The namespace used for file read/write operations
Using system. Text. regularexpressions; // This Is The namespace of the regular expression.
Int totalsourcecodelines = 0; // defines global variables.
Public int getsourcecodelins (string projectpath) // The parameter is the path of the source file, for example, D: \ sourcecode \ mycode
{
Calculatetotalcodelins(Projectpath); // call another function
Return totalsourcecodelines;
}
Private voidCalculatetotalcodelins(String projectpath)
{
// Traverse all directories
Directoryinfo dir = new directoryinfo (projectpath );
Foreach (directoryinfo dirinfo in Dir. getdirectories ())
Calculatetotalcodelins (projectpath + "\" + dirinfo. Name); // recursive call
Traverse all source files in the directory
Foreach (fileinfo in Dir. getfiles ())
{
If (RegEx. ismatch (fileinfo. name ,@". *\. (h | CPP) ") // you can use regular expressions to filter different source files. Here is the c ++ source file.
Totalsourcecodelines + = calculatecodelines (projectpath + "\" + fileinfo. Name); // call another function to calculate the number of lines in each source file.
}
}
// Calculate the number of lines in each source file
Private int calculatecodelines (string sourefilepath)
{
Filestream fstream = new filestream (sourefilepath, filemode. Open );
Streamreader reader = new streamreader (fstream );
Int COUNT = 0;
While (reader. Readline ()! = NULL)
{
Count ++;
}
Reader. Close ();
Fstream. Close ();
Return count;
}
Of course, the number of lines calculated in this way may not be accurate. You can consider how many source files are in total, and then the average number of line header files and spaces in each source file. Then, the number of lines minus these lines is relatively accurate.