Search code examples
carraysstringfgetsstrtok

Array of strings from single line in a file


I would like to get an array of strings from a .txt file. I tried using fgets then strtok to separate the strings. I think my fgets is wrong but I dont understand how to get to what I want.

char* str[numWords];
char line[] = fgets(str, numCharTotal, filep);
char delim[] = " ";
int j;
for(j = 0; j != numWords; j++)
{
       str[j]= strtok(line, delim);
}

In other words, I have a .txt file

This is a txt file

and I want to be able to have it in the form

char* str[] = {"This","is","a","txt","file"};

printf("%s", str[0])  //then "This" is printed
//...
//Till last word of txt file
//...
printf("%s", str[4])  //then "file" is printed


Solution

  • fgets will read a line from your file and store it in a string. You need to allocate memory for you buffer (char array line in your code). After calling strtok with the char array line as the first parameter, loop through calling strtok passing in NULL for the first parameter. If you continue to pass the char array line, you will only get the first token (word) for each iteration of the loop.

    char *str[numWords];
    char line[numCharTotal];
    char delim[] = " ";
    int j = 0;
    
    fgets(line, numCharTotal, filep);
    
    char *token = strtok(line, delim);
    while (token != NULL) {
        str[j] = token;
        ++j;
        token = strtok(NULL, delim);
    }
    
    for (int i = 0; i < numWords; ++i) {
        printf("%s\n", str[i]);
    }