-1

trying to create a code in C. First of all, I can't use the string.h library or any other that helps similarly. The input will be from command line like: ./program pattern file, I already succeed to open the file and write line of the file to an array, but now I have to compare the pattern a get with the line in file. If there is written the pattern, I have to printf the whole line.

For the input I use:

char array[1000]; // hope 1000 will be enough

char *pattern= argv[1];

For the scanning I use:

while (fscanf(f,"%c", &temp)!= EOF){
        if (temp=='\n'){
             Algoritm...
        }
        add to array( array[i++]=temp) - already works`

And If I get end of line, I do not When the '\n' ocures, I need to start the algorithm to find out if the small string is in the line.

My questions:

How can I compare these "strings"? efficiently?

How to get know the size of pattern I get as input? (I think I need that to do the algorithm)

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

2 Answers2

0

I suppose you are working on linux.

For your first question. memmem() should find the needle in your haystack;

From the memmem() manpage:

The memmem() function finds the start of the first occurrence of the substring needle of length needlelen in the memory area haystack of length haystacklen.

memmem returns:

The memmem() function returns a pointer to the beginning of the substring, or NULL if the substring is not found.

http://man7.org/linux/man-pages/man3/memmem.3.html

For your second question: How to find the length of argv[] in C

Benjamin
  • 1
  • 1
  • This isn't an answer. The question states *"I can't use the string.h library or any other that helps similarly."* And your second part directs the reader to another question, with no actual solution proposed here. – Weather Vane Mar 20 '19 at 10:19
0

You can write your own find function.

int find(char *array, char *pattern) {
    char *ap, *aap, *pp;
    for(ap=array; *ap; ap++) {
        for(pp=pattern, aap=ap; *aap && *pp && *pp==*aap; aap++, pp++); 
        if(*pp=='\0') return ap-array;
    }
    return -1;
}

The outer loop loops over your line 1 char a loop. It's the start point for the compare in the inner loop. The inner loop loops over your pattern and the line while

  • pattern not at end
  • line not at end
  • pattern char equals line char

without loop body.

If the pattern end is reached it was found and the function returns the found position in the line.

Holger
  • 899
  • 2
  • 7
  • 12