Reading from file in C including char and integer

Here is a simple code that do the job.

First put your text inside a test.txt file, save it in C source code path.

test.txt

A17ke4004       44         66      84
A17ke4005       33         62      88
A17ke4008       44         66      86

Code

#include <stdio.h>

int main (void)
{

        FILE *fp = NULL;
        char *line = NULL;
        size_t len = 0;
        size_t read = 0;
        char string[10][32];
        int a[10], b[10], c[10];
        int count = 0;

        fp = fopen("test.txt", "r");

        if(fp != NULL){
            while((read = getline(&line, &len, fp)) != -1){
                sscanf(line, "%s%d%d%d", string[count], &a[count], &b[count], &c[count]);
                printf("<%s> - <%d> - <%d> - <%d>\n", string[count], a[count], b[count], c[count]);
                count++;
            }
        }else{
                printf("File can't open\n");
        }

        return 0;
}

Compile, Run

gcc -Wall -Wextra te.c -o te

./te

If you have more than 10 lines you should increase the arrays dimension.
Hope this help you.

Leave a Comment