Search code examples
arrayscparsingiofread

How to read from a file and parse it


I have a file .txt containing some values formatted like this:

0,30,25,10

Now, I open up the file and store it into an array

char imposta_tratt[300]; 
FILE *fp;
fp = fopen("/home/pi/Documents/imposta_trattamento.txt", "r");
if (fp == 0) return;
fread(imposta_tratt, sizeof(imposta_tratt), 1, fp);
fclose(fp);

Now I expect to have the array filled with my data. I have the values separated by a , so I go on and parse it:

const char delim[2] = ",";
int t=0;
char *token = strtok(imposta_tratt, delim);
    while (token!=NULL){
    
        strcpy(tratt[t],token);
        token = strtok(NULL, delim);
        tratt[t]=token;
        t++;
    }

Here, referring to what's in the file .txt, I expect to have tratt[0]=0; tratt[1]=30; tratt[2]=25; and so on, but seems like I am missing something since it's not like this.

All I want is to have the values of the txt file stored in single variables. Can someone help?


Solution

  • What you are trying to achieve can simply be done using fgets():

    bool read_file_content(const char *filename, const size_t tsizemax, int tratt[tsizemax], size_t *tsize, const char *delim)
    {
        // Attempt to open filename.
        FILE *fp = fopen(filename, "r");
        if (!fp) return false; // Return false upon failure.
        
        // Try to read one line. If you have more, you need a while loop.
        char imposta_tratt[300];
        if (!fgets(imposta_tratt, sizeof imposta_tratt, fp)) {
            fclose(fp);
            return false;
        }
        
        *tsize = 0;
        char tmp[300]; // Temporary buffer. Used for conversion into int.
        char *token = strtok(imposta_tratt, delim);
        
        while (token && *tsize < tsizemax) {
            strncpy(tmp, token, sizeof tmp);
            tratt[(*tsize)++] = atoi(tmp);
            
            token = strtok(NULL, delim);
        }
        
        fclose(fp);
        return true;
    }
    
    • const char *filename: The file you want to parse.
    • const size_t tsizemax: The maximum size of your tratt array. It is important to control the size, otherwise your code will have buffer overflow (think of when your file has more than 100 tokens, for example).
    • int tratt[tsizemax]: The array that will hold the values.
    • size_t *tsize: The number of tokens read (used in combination of tsizemax).
    • const char *delim: The delimiter(s), in your case a ,.

    This is your main():

    int main(void)
    {
        int tratt[100];
        size_t size = 0;
        
        if (!read_file_content("in.txt", 100, tratt, &size, ",")) {
            puts("Failed");
            return 1;
        }
        
        for (size_t i = 0; i < size; ++i)
            printf("%d\n", tratt[i]);
    }
    

    Output:

    0
    30
    25
    10