I have two different text files, one of them contains a text, the other one works as a dictionary. The dictionary has some words line by line with their description beside them separated by a comma. I'm supposed to search for all these words in the text and then replace them with their description.

I thought after opening both for reading, I should load their contents into two arrays, I'm just a bit confused about the dictionary part since it should be read line by line and then each line should be broken into two parts.

I just really need some ideas on how to start this task.

So far I have this:

void open_file(char* text, char* dict, char* final) {

    FILE *t, *d, *f;

    t = fopen(text, "r");
    d = fopen(dict, "r");
    f = fopen(final, "w");

    fseek(d, 0, SEEK_END);
    long fsize = ftell(d);
    fseek(d, 0, SEEK_SET);
    char line[fsize + 1];
    char * x[fsize + 1];

    int i=0;

    while (!feof(d)){
        fgets(line,sizeof line,d);
        x[i] = strdup(line);
        i++;
    } 

    fclose(t);
    fclose(d);
    fclose(f);
}

int main() {
    open_file("text.txt","dict.txt","final.txt");
    return 0;
}

the first mistake is line 13: you are allocating an array of fsize number of pointers -- why??? If the file size is 1 Meg do you really need 1 million pointers? A much better and more efficient way to do it is to use a linked list of lines, something like this would do.

struct node
{
   char* word;
   char* line;
   struct node* next;
}

Now read the dictionary file and create the linked list. After that, the dictionary FILE can be closed.

Next, open the other test file and read it line-by-line. For each word in the line, search the word in the linked list. When the word is found replace it with the 'line' member of the node structure.

You will probably want to use a different char buffer for this, which can be used to create a new line without affecting the contents of the line buffer used to read the data file. It's a lot easier that way because you're just concantinating strings into that temp buffer.

for each line in the file
   for each word on the line
      is the word in the dictionary linked list?
         yes, then copy 'line' member of node into temp buffer
         no, then copy word from the line into temp buffer
   end for word
end for each
write temp buffer to output file
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.