Search code examples
cfilestructio

How to create struct of every word in .txt file in C?


if given a short .txt file that contained the following content, how would you go about creating a struct for every word in a specific line in the file and determining if it had an * before it

Sample File:

a *b c 
*d e f

I have created this structs:

typedef struct Unit
{
    bool hasStar;
    char variable[1];
} unit;

So I would want to create a struct for a, *b, and c for example. I'm not sure how to do this, so any help on how best to approach this would be amazing


Solution

  • Firstly, you have to change char variable[1] to char varibale[3] at least for storing the string "*a" for example.

    You can get line by line from the file using fgets then using strtok to separate the line by space character.

    FILE *fp = fopen("intput.txt", "r");
    if(!fp)
      // handle error.
    char line[256];
    while(fgets(line, sizeof(line), fp) {
        // using strtok to split each line
    }
    

    For spliting the line using strtok and verify the star symbol * at the begin of word:

    char * token = strtok(line, " ");
    while (token != NULL) {
        strcpy(units[i].variable, token);
        if (token[0] == '*')
           units[i].hasStar = true;
        else
            units[i].hasStar = false;
        strtok(NULL, " ");
        i++;
    }
    

    Before while loop of fgets, you have to declare the size of units and initialize i first, for example the code below, i initialize the size of array units that is eaqual to 100:

    unit units[100];
    int i = 0;