注意:
1.变量名和函数名不要混淆调用
2.不要对文件夹进行文件的操作,没有权限
3.递归调用注意初始化变量
1 //
2 // main.m
3 // CodeLineCount
4 //
5 // Created by hellovoidworld on 14-11-18.
6 // Copyright (c) 2014年 com.hellovoidworld. All rights reserved.
7 //
8
9 #import <Foundation/Foundation.h>
10
11 // 计算文件夹或文件内所有代码行数
12 NSInteger codeLineCount(NSString *path)
13 {
14 NSError *error;
15
16 // 单例模式创建 NSFileManager
17 NSFileManager *fileManager = [NSFileManager defaultManager];
18
19 BOOL isDirectory = NO;
20 BOOL isFileExist = [fileManager fileExistsAtPath:path isDirectory:&isDirectory];
21
22 // 文件是否存在
23 if (!isFileExist)
24 {
25 NSLog(@"%@-->文件或文件夹不存在!", path);
26 return 0;
27 }
28
29 // 如果是文件夹,进行递归调用
30 if (isDirectory)
31 {
32 // NSLog(@"文件夹: %@", path);
33
34 NSInteger lineCount = 0; // 代码行数
35
36 // 获取文件夹下的所有内容,包括子文件夹和文件
37 NSArray *subPaths = [fileManager contentsOfDirectoryAtPath:path error:&error];
38
39 if (error != nil)
40 {
41 NSLog(@"Fail to read the directory, the error is %@", error);
42 }
43
44 for (NSString *subPath in subPaths)
45 {
46 NSString *fullSubPath; // 全路径的文件名
47 fullSubPath = [NSString stringWithFormat:@"%@/%@", path, subPath]; // 取出来的文件名不带路径
48 lineCount += codeLineCount(fullSubPath);
49 }
50
51 return lineCount;
52 }
53 else
54 {
55 NSInteger lineCount = 0; // 代码行数
56
57 // 取得文件扩展名
58 NSString *fileExtension = [[path pathExtension] lowercaseString];
59
60 // 过滤非代码文件
61 if (![fileExtension isEqualToString:@"h"]
62 && ![fileExtension isEqualToString:@"m"]
63 && ![fileExtension isEqualToString:@"c"])
64 {
65 return 0;
66 }
67
68 NSString *fileContent = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
69
70 if (error != nil)
71 {
72 NSLog(@"Read fail, error is %@", error);
73 }
74
75 NSArray *codeLinesArray = [fileContent componentsSeparatedByString:@"
"];
76 lineCount = [codeLinesArray count];
77
78 NSLog(@"%@的代码行数是%ld", path, lineCount);
79 return lineCount;
80 }
81 }
82
83 int main(int argc, const char * argv[]) {
84 @autoreleasepool {
85
86 NSInteger lineCount = codeLineCount(@"/Users/hellovoidworld/Study");
87 NSInteger lineCount2 = codeLineCount(@"/Users/hellovoidworld/Desktop/oc");
88
89 NSLog(@"所有源码文件的总行数是%ld", lineCount + lineCount2);
90
91 }
92
93 return 0;
94 }
