search.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. int main (int argc, char **argv) {
  5. char *file, *string, *ptr1, *ptr2;
  6. int len, ctr;
  7. if (argc == 1) {
  8. printf ("File to read: ");
  9. scanf ("%s", &file);
  10. printf ("String to search for: ");
  11. scanf ("%s", &string);
  12. } else if (argc == 2) {
  13. file = argv[1];
  14. printf ("String to search for: ");
  15. scanf ("%s", &string);
  16. } else if (argc == 3) {
  17. file = argv[1];
  18. string = argv[2];
  19. } else {
  20. printf ("String Search\n\n");
  21. printf ("This program searches for the first occurrence of the given substring in the given file.\n\n");
  22. printf ("Usage:\n");
  23. printf ("\t$ %s [file] [string]\n", argv[0]);
  24. printf ("where [file] is the ASCII file to search and [string] is the string to search for.\n");
  25. return EXIT_SUCCESS;
  26. }
  27. /* Testing */
  28. printf ("Testing");
  29. /* Read the file and compare to the string */
  30. FILE *fp = fopen(file, "r");
  31. if (fp == NULL) {
  32. perror ("Error");
  33. return EXIT_FAILURE;
  34. }
  35. len = strlen(string);
  36. ptr1 = file;
  37. ptr2 = ptr1;
  38. while (*ptr2) {
  39. while (*ptr1 != string[0] && *ptr1) { ++ptr1; }
  40. ptr2 = ptr1;
  41. for (ctr = 0; ctr < len; ++ctr) {
  42. if (*ptr2 != string[ctr]) {
  43. break;
  44. }
  45. if (len - ctr == 1) {
  46. printf ("Substring found at %d\n", ctr);
  47. return EXIT_SUCCESS;
  48. }
  49. ++ptr2;
  50. }
  51. }
  52. printf ("Substring \"%s\" not found in file \"%s\"\n", string, file);
  53. return EXIT_SUCCESS;
  54. }