Main.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include <dirent.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. const char** filters = NULL;
  5. int filterAmount = 0;
  6. char path[PATH_MAX] = {'\0'};
  7. int pathLength = 0;
  8. int allLines = 0;
  9. void appendToPath(const char* s) {
  10. for(int i = 0; pathLength < (PATH_MAX - 1) && s[i] != '\0'; i++) {
  11. path[pathLength++] = s[i];
  12. }
  13. path[pathLength] = '\0';
  14. }
  15. int enterPath(const char* name) {
  16. int length = pathLength;
  17. appendToPath("/");
  18. appendToPath(name);
  19. return length;
  20. }
  21. void resetPath(int marker) {
  22. path[marker] = '\0';
  23. pathLength = marker;
  24. }
  25. void countLines() {
  26. FILE* file = fopen(path, "r");
  27. if(file == NULL) {
  28. return;
  29. }
  30. int lines = 0;
  31. while(1) {
  32. int c = fgetc(file);
  33. if(c == EOF) {
  34. lines++;
  35. break;
  36. } else if(c == '\n') {
  37. lines++;
  38. }
  39. }
  40. printf("%s = %d\n", path, lines);
  41. allLines += lines;
  42. fclose(file);
  43. }
  44. void handleFile(const char* name) {
  45. int end = strlen(name);
  46. for(int i = 0; i < filterAmount; i++) {
  47. int l = strlen(filters[i]);
  48. if(end >= l && !strcmp(filters[i], name + (end - l))) {
  49. int marker = enterPath(name);
  50. countLines();
  51. resetPath(marker);
  52. return;
  53. }
  54. }
  55. }
  56. void scanFolder() {
  57. DIR* dir = opendir(path);
  58. if(dir == NULL) {
  59. return;
  60. }
  61. while(1) {
  62. struct dirent* entry = readdir(dir);
  63. if(entry == NULL) {
  64. break;
  65. } else if(!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
  66. continue;
  67. } else if(entry->d_type == DT_DIR) {
  68. int marker = enterPath(entry->d_name);
  69. scanFolder();
  70. resetPath(marker);
  71. } else if(entry->d_type == DT_REG) {
  72. handleFile(entry->d_name);
  73. }
  74. }
  75. closedir(dir);
  76. }
  77. int main(int argAmount, const char** args) {
  78. if(argAmount < 3) {
  79. if(argAmount > 0) {
  80. printf("%s <path> <ending_1> [ending_2] ...\n", args[0]);
  81. } else {
  82. puts("... <path> <ending_1> [ending_2] ...");
  83. }
  84. return 0;
  85. }
  86. filters = args + 2;
  87. filterAmount = argAmount - 2;
  88. appendToPath(args[1]);
  89. scanFolder();
  90. printf("Lines: %d\n", allLines);
  91. return 0;
  92. }