fgrep.c 1003 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2014-2018 K. Lange
  5. *
  6. * fgrep - dump grep
  7. *
  8. * Locates strings in files and prints the lines containing them,
  9. * with extra color identification if stdout is a tty.
  10. */
  11. #include <stdio.h>
  12. #include <fcntl.h>
  13. #include <unistd.h>
  14. #include <string.h>
  15. #define LINE_SIZE 4096
  16. int main(int argc, char ** argv) {
  17. if (argc < 2) {
  18. fprintf(stderr, "usage: %s thing-to-grep-for\n", argv[0]);
  19. return 1;
  20. }
  21. char * needle = argv[1];
  22. char buf[LINE_SIZE];
  23. int ret = 1;
  24. int is_tty = isatty(STDOUT_FILENO);
  25. while (fgets(buf, LINE_SIZE, stdin)) {
  26. char * found = strstr(buf, needle);
  27. if (found) {
  28. if (is_tty) {
  29. *found = '\0';
  30. found += strlen(needle);
  31. fprintf(stdout, "%s\033[1;31m%s\033[0m%s", buf, needle, found);
  32. } else {
  33. fprintf(stdout, "%s", buf);
  34. }
  35. ret = 0;
  36. }
  37. }
  38. return ret;
  39. }