This small MATLAB utility recursively counts code, comment and blank lines
across files in a folder (or for a supplied file list) and writes a plain-text
report named lineCount.txt.
countLines.m— Main function that scans files, classifies lines, and writeslineCount.txt(also contains the helperparseFilesub-function).main.m— Example runner that demonstrates how to callcountLines.lineCount.txt— Example output generated by the utility.
- MATLAB (R2019b or later recommended for
argumentsvalidation). - No additional toolboxes required.
Call the function from the MATLAB command window, from a script, or use the
provided main.m example. Examples:
% Count all .m files under a folder and write report to current folder
countLines('C:\path\to\project')
% Specify file types and an output directory
countLines('C:\path\to\project', {'.m', '.cpp'}, {}, 'C:\out')
% Provide an explicit list of files
countLines({'file1.m', 'file2.cpp'}, {'.m', '.cpp'})countLines(inputPath, fileTypes, ignoreFiles, saveDir)
inputPath(char|string|cell): A folder path (to search recursively) or a cell array of file paths to analyze.fileTypes(cell): Cell array of extensions to include, e.g.{'.m', '.cpp'}. Default:{'.m'}.ignoreFiles(cell): Filenames (name+ext) to ignore. Default:{}.saveDir(char|string): Directory wherelineCount.txtwill be written. Default: current working directory.
lineCount.txt contains one line per file with counts and a grand total
section. Example layout:
File : Code | Comments | Blank | Total
------------------------------------------------------
C:\path\to\file1.m : 100 | 20 | 10 | 130
Grand Totals:
Code : 100
Comments : 20
Blank : 10
Total : 130
- Lines beginning with
%(MATLAB) or//(C/C++) are considered comment lines. - Block C/C++ comments using
/* ... */are tracked and counted as comment lines. - Block MATLAB comments using
%{ ... %}are tracked and counted as comment lines. - Count “mixed” lines (code + inline comment).
- Inline comments on the same line as code are counted as code lines.
- The function uses simple heuristics and may misclassify complex constructs.
- To add support for additional file types, provide their extensions in
fileTypes. - To change classification behavior (for example, to treat inline comments
differently), edit the
parseFilesub-function insidecountLines.m. - To change output format (CSV, JSON), modify the write section in
countLines.mwherelineCount.txtis created.
This project is provided under the MIT license. See LICENSE.