Hi,
I am working my way through a C Programming book but I am confused by this extract of code from book, which is suppose to locate lines ending with 'ould' and print them.
Code:
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */
int getline(char line[], int max) int strindex(char source[], char searchfor[]);
char pattern[] = "ould"; /* pattern to search for */
/* find all lines matching pattern */ main()
{ char line[MAXLINE]; int found = 0;
while (getline(line, MAXLINE) > 0) if (strindex(line, pattern) >= 0) {
printf("%s", line); found++;}
return found; }
/* getline: get line into s, return length */ int getline(char s[], int lim) {
int c, i;
i = 0; while (--lim > 0 && (c=getchar()) != EOF && c != '\n')
s[i++] = c; if (c == '\n')
[IMG]file:///page63image24688[/IMG]
[IMG]file:///page63image24960[/IMG]
[IMG]file:///page63image25232[/IMG]
s[i++] = c;
s[i] = '\0';
return i;}
/* strindex: return index of t in s, -1 if none */int strindex(char s[], char t[]) {
int i, j, k;
for (i = 0; s[i] != '\0'; i++) { for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++)
; if (k > 0 && t[k] == '\0')
}
return i;
return -1;}
What does the following:
Code:
#define MAXLINE 1000
actually mean, is 'MAXLINE' a built in function of C or something which they have created?
Then they use:
Code:
getline(char line [], int max)
So 'getline' is fairly self explanatory, then they indicate the type or result they are expecting which is 'char' for character. Now is that being put into a array, I am wondering because of '[]'? Furthermore, what is the 'int max' for?
Everything after that makes sense, they create a char array but why does it equal "ould", I know that the snipet that they are searching for.
Code:
char pattern[] = "ould";
Now we create another array called line, which refers to that 'MAXLINE' from earlier?
Code:
main()
{ char line[MAXLINE]; int found = 0;
while (getline(line, MAXLINE) > 0) if (strindex(line, pattern) >= 0) {
printf("%s", line); found++;}
return found;
}
Then we use a while loop, so while there is a line search for pattern and then print the string.