-5

How to read and store each column in the following text from a file into an array

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

The first column should be string and the rest should be integer

Jabberwocky
  • 40,411
  • 16
  • 50
  • 92
  • possible duplicate - https://stackoverflow.com/questions/16620779/printing-tokenized-data-from-file-in-c – vbRocks Nov 29 '17 at 13:51
  • 1
    Possibly, but I suggest using more delimiter characters than just a space. Perhaps add `'\t'` in case the data is tabbed, and `'\n'` to clean off the trailing newline from `fgets`. – Weather Vane Nov 29 '17 at 13:54

1 Answers1

1

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.

EsmaeelE
  • 1,681
  • 5
  • 15
  • 22
Fabio_MO
  • 638
  • 1
  • 12
  • 22
  • Beautify code indents, use meaningful variable: `FILE *fp;`(file pointer), initialize all variables – EsmaeelE Nov 29 '17 at 15:03
  • Compiling with `gcc -Wall -Wextra te.c -o te te.c: In function ‘main’: te.c:18:42: warning: comparison between signed and unsigned integer expressions [-Wsign-compare] while((read=getline(&line, &len, fp)) != -1){ ` – EsmaeelE Nov 29 '17 at 15:47
  • Change `size_t read = 0;` to `ssize_t read = 0;`, see [example](http://man7.org/linux/man-pages/man3/getline.3.html), comparison between unsigned/singed integer not good – EsmaeelE Nov 29 '17 at 15:48
  • C standard [main()](https://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c) return type, arguments – EsmaeelE Nov 29 '17 at 15:51