Reputation: 25
I have a text file that contains text similar to this:
01234 Johnathan Doe 1 RG
12345 Jane Doe 3 OC
My question is: how can I define a struct that can contain the information contained in the file, using an array (of structs) to store the data read from the file? Of course the file give me in a row: the badge,name,surname,year and status in this order, separated from a space each other. Also I cannot add other libraries in addition to those already present.
#include <stdio.h>
#include <string.h>
struct student {
int *badge;
char *name;
char *surname;
int *year;
char *status;
};
typedef struct student Student;
int main(){
}
Upvotes: 0
Views: 57
Reputation: 519
Good job on the struct, except you can just store your numbers as integers, no need to have them as pointers.
You might want to take a look at fopen: opens a file.
And fscanf, which reads in from the file.
fscanf takes in type specifier, so, in this case it would be “%i, %s, %s, %i, %s”, then the next arguments would be the variables in the order where you want to store what you read in.
So have local variables for the above case. And wrap the fscanf in a while loop checking it’s return value (whether EOF or error occurred).
Inside the loop, you can create your struct and initialize the members with the respective local variables. That struct will represent a line. Then store the struct in an array, so the array will represent the file, the array will get populated by the while loop.
Upvotes: 2