Hacker News new | ask | show | jobs
by kazinator 1914 days ago
New version:

- swap pointers to flip buffers instead of strcpy

- handle corner case of directory printed after contents (find -depth) by avoiding printing nothing but spaces, or nothing but spaces followed by a slash

  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>

  int main(void)
  {
    typedef char buf_t[FILENAME_MAX];
    buf_t buf[2] = { "" };
    buf_t *pline = &buf[0], *line = &buf[1];

    while (fgets(*line, sizeof *line, stdin)) {
      buf_t *tmp;
      char *l = *line, *p = *pline, *nl = strchr(l, '\n');

      if (nl)
        *nl = 0;

      while (*l && *p) {
        char *op = l;

        if (*p == '/' && *l == '/')
          p++, l++;

        size_t lp = strcspn(l, "/");
        size_t lo = strcspn(p, "/");

        if (lp == lo && !strncmp(l, p, lp)) {
          l += lp;
          p += lp;
          continue;
        }

        l = op;
        break;
      }

      if (l[0] && (l[1] || l[0] != '/'))
        printf("%*s%s\n", (int) (l - *line), "", l);
      else
        puts(*line);

      tmp = pline, pline = line, line = tmp;
    }

    return feof(stdin) ? EXIT_SUCCESS : EXIT_FAILURE;
  }