Hi all.
The code works as expected(display words starting with brown). What if I don't know in advance how many words of this type a document contains? How can I dynamically increase the size of a multi-dimensional array, or an array of pointers? Is there a function in the C library that can do this?
Thanks in advance.
test.txt
Code:
How now "brownone" cow. A cow has four "browntwo" legs.
output
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DOCUMENT_LENGTH 100
int main(void)
{
char *loc, *search_string = "brown";
char buffer[DOCUMENT_LENGTH], string[2][10];
char temp[DOCUMENT_LENGTH];
FILE *file;
int bufferctr, ctr1 = 0, ctr2 = 0, ch, ctr;
if((file = fopen("test.txt", "r")) == NULL)
{
perror("Error");
exit(EXIT_FAILURE);
}
if(fgets(buffer, DOCUMENT_LENGTH, file) == NULL)
{
perror("Error");
exit(EXIT_FAILURE);
}
while((loc = strstr(buffer, search_string)) != NULL)
{
bufferctr = loc - buffer;
while((ch = buffer[bufferctr]) != '"')
{
string[ctr1][ctr2] = ch;
ctr2++;
bufferctr++;
}
string[ctr1][ctr2] = '\0';
bufferctr++;
strcpy(temp, &buffer[bufferctr]); // temp needed because strcpy(buffer, &buffer[buffer[ctr]) overlap
strcpy(buffer, temp);
ctr1++;
ctr2 = 0; // reset
bufferctr = 0; // reset
}
for(ctr = 0; ctr < 2; ctr++)
{
printf("%s\n", string[ctr]);
}
return 0;
}