Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

read a file line by line c++ struct site:stackoverflow.com

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    char name[100];
    int age;
    float height;
} PERSON;

int
main()
{
    PERSON *X = NULL;
    FILE *f;
    int i;
    PERSON *p;
    size_t count = 0;
    size_t alloc = 0;

    f = fopen("filename.txt", "r");

    while (1) {
        if (count >= alloc) {
            alloc += 100;
            X = realloc(X,sizeof(PERSON) * alloc);
        }

        p = &X[count];

        if (fscanf(f, "%s%d%f", p->name, &p->age, &p->height) == EOF)
            break;

        ++count;
    }

    fclose(f);

    // trim the array to what was actually used
    X = realloc(X,sizeof(PERSON) * count);

    p = X;
    for (i = 0;  i < count;  i++, p++)
        printf("%s
%d 
%f
", p->name, p->age, p->height);

    return 0;
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #read #file #line #line #struct
ADD COMMENT
Topic
Name
3+9 =