scanner.c

Fri, 21 Oct 2011 15:09:26 +0200

author
Mike Becker <universe@uap-core.de>
date
Fri, 21 Oct 2011 15:09:26 +0200
changeset 23
778388400f7b
parent 22
4508da679ffb
child 25
802c5382f499
permissions
-rw-r--r--

encapsulated scanner arguments + enabled optimizer + empty file is no bfile

/*
 * scanner.c
 *
 *  Created on: 23.05.2011
 *      Author: Mike
 */


#include "scanner.h"
#include "suffix_fnc.h"
#include "bfile_heuristics.h"
#include <sys/stat.h>

int scanDirectory(scanner_t scanner, settings_t* settings) {

  DIR *dirf;
  struct dirent *entry;
  int lines, a;
  int lineSum = 0;
  bool bfile;
  struct stat statbuf;

  if ((dirf = opendir(scanner.dir)) == NULL) {
    printf(scanner.dir);
    perror("  Directory access failed");
    return 0;
  }

  while ((entry = readdir(dirf)) != NULL) {
    if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
      /* Construct tree view and absolute pathname strings */
      char entryname[strlen(entry->d_name)+scanner.spaces];
      for (int t = 0 ; t < scanner.spaces ; t++) {
        entryname[t]=' ';
      }
      entryname[scanner.spaces] = 0;
      strcat(entryname, entry->d_name);
  
      char filename[(1+strlen(scanner.dir)+strlen(entry->d_name))];
      strcpy(filename, scanner.dir);
      strncat(filename, &settings->fileSeparator, 1);
      strcat(filename, entry->d_name);

      /* Check for subdirectory */
      if (stat(filename, &statbuf) == 0) {
        if (!(statbuf.st_mode & S_IFREG)) {
          printf("%-60s\n", entryname);
          if (settings->recursive && (statbuf.st_mode & S_IFDIR)) {
            lineSum += scanDirectory(
                (scanner_t) {filename, scanner.spaces+1}, settings);
          }
          continue;
        }
      } else {
        perror("  Error in stat call");
        continue;
      }

      /* Count lines */
      lines = 0;
      bfile = false;
      bfile_reset(settings->bfileHeuristics);
      if (testSuffix(filename, settings)) {
        FILE *file = fopen(filename, "r");
        if (file == NULL) {
          printf(entryname);
          perror("  File acces failed");
          continue;
        }

        do {
          a = fgetc(file);

          bfile = bfile_check(settings->bfileHeuristics, a);

          if (a == 10) {
            lines++;
          }
        } while (!bfile && a != EOF);
        fclose(file);

        /* Print and sum line count */
        if (bfile) {
          if (!settings->matchesOnly) {
            printf("%-60s%19s\n", entryname, "binary");
          }
        } else {
          lineSum += lines;
          printf("%-60s%13d lines\n", entryname, lines);
        }
      } else {
        if (!settings->matchesOnly) {
          /* Print hint */
          printf("%-60s%19s\n", entryname, "no match");
        }
      }
    }
  }

  closedir(dirf);

  return lineSum;
}

mercurial