#import <Foundation/Foundation.h> int codeLineCount(NSString *path) { //1.获得文件管理者 NSFileManager *mgr = [NSFileManager defaultManager]; //判断path是文件夹还是文件路径 BOOL dir = NO; // 标记是否为文件夹 //这个路径是否存在 BOOL exist = [mgr fileExistsAtPath:path isDirectory:&dir]; //3.如果不存在 if(!exist) return 0; //4路径存在 if(dir) { // NSLog(@"是个文件夹"); //装着当前文件夹下面的所有的内容(文件夹,文件) NSArray *array = [mgr contentsOfDirectoryAtPath:path error:nil]; int count = 0; //遍历数组中的所有文件名 for(NSString *filename in array){ //子文件(夹)的全路径 NSString *fullPath = [NSString stringWithFormat:@"%@/%@",path,filename]; //循环调用 count += codeLineCount(fullPath); } return count; } else { //判断文件名的扩展名 NSString *extension = [[path pathExtension] lowercaseString]; if(!([extension isEqualToString:@"h"] || [extension isEqualToString:@"m"] || [extension isEqualToString:@"c"]) ){ //文件的扩展名不是h,而且不是m,而且不是c return 0; } //文件 //1.加载文件内容 NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; //2.将文件内容分隔为每一行 //按\n分隔形成一个字符数组 NSArray *array = [content componentsSeparatedByString:@"\n"]; NSString *str = [path stringByReplacingOccurrencesOfString:@"/Users/laouhn/Documents/Project" withString:@""]; NSLog(@"%@ - %ld", str,array.count); return (int)array.count; } } int main(int argc, const char * argv[]) { int count = codeLineCount(@"/Users/laouhn/Documents/Project"); NSLog(@"%d", count); return 0; } //void test() //{ // NSString *str = @"jack\nrose\njim\njake"; // //向文件中写东西 // [str writeToFile:@"/Users/laouhn/Desktop/crayons.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil]; // //按字符分隔 // NSArray *array = [str componentsSeparatedByString:@"\n"]; // // //} //