I do not know what your add_dictionary_first
function does, nor do I know if the result of fgets
becomes the same as the constant address "32"
. If what you tried was to save the first word of each line, then you should know that strtok
returns the same pointer whenever it is called, so if you read the first line and get the first word, everything will be fine, but then you read another line and call strtok
, the content of the "previous" pointer remains with the content of the first word of the last line that departed with strtok
.
To all this, one of the solutions is to create a copy of the chain returned by strtok
, in the following lines:
while (fgets(line, LONG_MAX_LINE, date ) != "32") {
word = strtok(line, exeption); /*first word*/
add_dictionary_first(D_first, j, word);
j++;
}
With the following 1 :
/* ... while(fgets... { */
word = strtok(line, exeption); /*first word*/
int len = strlen(word); /* longitud de la primera palabra. */
char *tword = calloc(1, len + 1); /* en caso de emergencia, memoria dinamica. */
memcpy(tword, word, len); /* Clonamos el contenido del puntero de strtok */
add_dictionary_first(D_fird, j, word); /* Y por ultimo agregamos al diccionario. */
j++;
/* } // Final del while. */
To achieve this, you must make #include
to the following headers to your .c
file:
#include <stdlib.h>
#include <string.h>
Within stdlib.h
you will find calloc
and others, which are functions you need when working with dynamic memory. Remember at the end of the program or when its life cycle is over, call free
with each dynamic memory block reserved with malloc
or calloc
.
The complete code would be this:
#include <stdlib.h>
#include <string.h>
/* ... Otras funciones... */
dictionary *load_word(int autor, dictionary *D_first) {
FILE *date;
char line[LONG_MAX_LINE];
char exeption[4] = " \n\t";
char *word;
int j=0;
if (autor == 1) {
if ((date = fopen("test.txt", "r")) == NULL) {
perror("robert_frost.txt");
}
while (fgets(line, LONG_MAX_LINE, date ) != "32") {
word = strtok(line, exeption); /*first word*/
int len = strlen(word); /* longitud de la cadena retornada por strtok */
char *tword = calloc(1, len + 1); /* +1 en caso de emergencia, memoria dinamica. */
memcpy(tword, word, len); /* Copiamos la cadena en la memoria reservada. */
add_dictionary_first(D_first, j, word);
j++;
}
fclose(date);
}
return D_first;
}
/* ... Otras, otras funciones... */
With that you should already see all the first words of each line.
1 : I've written the code in its head, if it does not work, let me know to fix it.
Greetings!