1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int main (int argc, char **argv) {
- char *file, *string, *ptr1, *ptr2;
- int len, ctr;
- if (argc == 1) {
- printf ("File to read: ");
- scanf ("%s", &file);
- printf ("String to search for: ");
- scanf ("%s", &string);
- } else if (argc == 2) {
- file = argv[1];
- printf ("String to search for: ");
- scanf ("%s", &string);
- } else if (argc == 3) {
- file = argv[1];
- string = argv[2];
- } else {
- printf ("String Search\n\n");
- printf ("This program searches for the first occurrence of the given substring in the given file.\n\n");
- printf ("Usage:\n");
- printf ("\t$ %s [file] [string]\n", argv[0]);
- printf ("where [file] is the ASCII file to search and [string] is the string to search for.\n");
- return EXIT_SUCCESS;
- }
- /* Testing */
- printf ("Testing");
- /* Read the file and compare to the string */
- FILE *fp = fopen(file, "r");
- if (fp == NULL) {
- perror ("Error");
- return EXIT_FAILURE;
- }
- len = strlen(string);
- ptr1 = file;
- ptr2 = ptr1;
- while (*ptr2) {
- while (*ptr1 != string[0] && *ptr1) { ++ptr1; }
- ptr2 = ptr1;
- for (ctr = 0; ctr < len; ++ctr) {
- if (*ptr2 != string[ctr]) {
- break;
- }
- if (len - ctr == 1) {
- printf ("Substring found at %d\n", ctr);
- return EXIT_SUCCESS;
- }
- ++ptr2;
- }
- }
- printf ("Substring \"%s\" not found in file \"%s\"\n", string, file);
- return EXIT_SUCCESS;
- }
|