[OC Foundation框架 - 20] 统计代码行数

注意:

1.变量名和函数名不要混淆调用
2.不要对文件夹进行文件的操作,没有权限
3.递归调用注意初始化变量
 
 //
// main.m
// CodeLineCount
//
// Created by hellovoidworld on 14-11-18.
// Copyright (c) 2014年 com.hellovoidworld. All rights reserved.
// #import <Foundation/Foundation.h> // 计算文件夹或文件内所有代码行数
NSInteger codeLineCount(NSString *path)
{
NSError *error; // 单例模式创建 NSFileManager
NSFileManager *fileManager = [NSFileManager defaultManager]; BOOL isDirectory = NO;
BOOL isFileExist = [fileManager fileExistsAtPath:path isDirectory:&isDirectory]; // 文件是否存在
if (!isFileExist)
{
NSLog(@"%@-->文件或文件夹不存在!", path);
return ;
} // 如果是文件夹,进行递归调用
if (isDirectory)
{
// NSLog(@"文件夹: %@", path); NSInteger lineCount = ; // 代码行数 // 获取文件夹下的所有内容,包括子文件夹和文件
NSArray *subPaths = [fileManager contentsOfDirectoryAtPath:path error:&error]; if (error != nil)
{
NSLog(@"Fail to read the directory, the error is %@", error);
} for (NSString *subPath in subPaths)
{
NSString *fullSubPath; // 全路径的文件名
fullSubPath = [NSString stringWithFormat:@"%@/%@", path, subPath]; // 取出来的文件名不带路径
lineCount += codeLineCount(fullSubPath);
} return lineCount;
}
else
{
NSInteger lineCount = ; // 代码行数 // 取得文件扩展名
NSString *fileExtension = [[path pathExtension] lowercaseString]; // 过滤非代码文件
if (![fileExtension isEqualToString:@"h"]
&& ![fileExtension isEqualToString:@"m"]
&& ![fileExtension isEqualToString:@"c"])
{
return ;
} NSString *fileContent = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; if (error != nil)
{
NSLog(@"Read fail, error is %@", error);
} NSArray *codeLinesArray = [fileContent componentsSeparatedByString:@"\n"];
lineCount = [codeLinesArray count]; NSLog(@"%@的代码行数是%ld", path, lineCount);
return lineCount;
}
} int main(int argc, const char * argv[]) {
@autoreleasepool { NSInteger lineCount = codeLineCount(@"/Users/hellovoidworld/Study");
NSInteger lineCount2 = codeLineCount(@"/Users/hellovoidworld/Desktop/oc"); NSLog(@"所有源码文件的总行数是%ld", lineCount + lineCount2); } return ;
}
上一篇:第三课:sea.js模块加载原理


下一篇:在Linux和Windows系统上安装Nginx服务器的教程