cmicrocontrollerfatfs

Reading data from a text file line by line into arrays using strtok in C


Currently trying to read data from a text file line by line using strtok and a space as a delimiter and save the info into different arrays. Im using the FatFs library to read the file from an sd card. Atm im only trying to read the first 2 elements from the line.

My text file looks like this:

223 895 200 200 87 700 700 700
222 895 200 200 87 700 700 700
221 895 200 200 87 700 700 700
222 895 200 200 87 700 700 700

My current code is something like this:

void sd_card_read()
{
char buffer[30];
char buffer2[10];
char buffer3[10];

int i=0;
int k=0;
int l=0;

int16 temp_array[500];
int16 hum_array[500];

char *p;


FIL fileO;
uint8 resultF;

    resultF = f_open(&fileO, "dados.txt", FA_READ);

    if(resultF == FR_OK)
    {

        UART_UartPutString("Reading...");
        UART_UartPutString("\n\r");


        while(f_gets(buffer, sizeof(buffer), &fileO))
        {
            p = strtok(buffer, " ");
            temp_array[i] = atoi(p);
            UART_UartPutString(p);
            UART_UartPutString("\r\n");

            p = strtok(NULL, " ");
            hum_array[i] = atoi(p);
            UART_UartPutString(p);
            UART_UartPutString("\r\n");


            i++;
        }

        UART_UartPutString("Done reading");

        resultF = f_close(&fileO);

    }


UART_UartPutString("Printing");
UART_UartPutString("\r\n");


for (k = 0; k < 10; k++) 
{
    itoa(temp_array[k], buffer2, 10);
    UART_UartPutString(buffer2);
    UART_UartPutString("\r\n");
}

for (l = 0; l < 10; l++) 
{
    itoa(hum_array[l], buffer3, 10);
    UART_UartPutString(buffer3);
    UART_UartPutString("\r\n");
}

}

The output atm is this:

223
0
222
0

etc..

895
0
895
0

etc..

After reading one time it puts the next position the value of 0 in both arrays, which is not what is wanted. Its probably something basic but cant see what is wrong.

Any help is valuable!


Solution

  • If we take the first line of the file

    223 895 200 200 87 700 700 700
    

    That lines is, including space and newline (assuming single '\n') 31 characters long. And since strings in C needs to be terminated by '\0' the line requires at least 32 characters (if f_gets works similar to the standard fgets function, and adds the newline).

    Your buffer you read into only fits 30 characters, which means only 29 characters of your line would be read and then the terminator added. So that means you only read

    223 895 200 200 87 700 700 70
    

    The next time you call f_gets the function will read the remaining

    0
    

    You need to increase the size of the buffer to be able to fit all of the line. With the current data it needs to be at least 32 characters. But be careful since an extra character in one of the lines will give you the same problem again.