In C, Recursively Find Substring In Char Array Given By User

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

void read(char* arr, const int len, FILE* in, FILE* out, char* prompt){
	fprintf(out, prompt);
	fflush(in);
	if(NULL == fgets(arr, len, in)){
		fprintf(out, "Error: Early end of input!\n");
		exit(1);
	}
	while(*arr){
		switch(*arr){
			case '\r':
			case '\n':
				*arr = '\0';
		}
		arr++;
	}
}

void locate(char* line, char* find, FILE* out){
	char* searchPtr = strstr(line, find);
	if(NULL == searchPtr) return;
	fprintf(out, "%s\n", searchPtr);
	searchPtr ++;
	locate(searchPtr, find, out);
}

void main(){
	const int MAX_LEN = 20;
	char line[MAX_LEN+1];
	char find[MAX_LEN+1];
	read(line, MAX_LEN, stdin, stdout, "Full text: ");
	read(find, MAX_LEN, stdin, stdout, "Find text: ");
	locate(line, find, stdout);
}
Download

Comments

Popular posts from this blog