Diablo - 1 year ago 61
C Question

# Creating arrays of structs using text file

Given a text file with a semi-known format. Total characters in 1 line will be less than 1000. Zinteger is just a normal integer but it serves a different purpose. String terminated via space.

String ZInteger Integer Integer

String ZInteger Integer Integer Integer Integer

So its a word followed by a number followed by pairs of numbers, but a random amount of pairs.

I want to store the string , Zinteger, and integer pairs for each line in a data structure.

So I tried an array where A[1] would be a struct that has String, Zinteger and the pairs of integers which will be another struct that has the integer pair. Heres what i tried.

``````typedef struct {
int num1;
int num2;
} ints_t;

typedef struct {
char term[1000];
int quantity(bad variable name, could be called alpha);
ints_t *pairs;
} info_t;
``````

Help is appreciated.

EDIT: Alright so im being too open. So ill just ask a simple question are the two structs I made viable and if not how do I make them viable and how do I malloc the structs and array.

Your structure looks reasonable, however, it is missing a field to store a count for the number of pairs:

``````typedef struct {
int num1;
int num2;
} int_pair_t;

typedef struct {
char term[1000];
int zinteger;    /* so named to avoid confusion */
int n_pairs;
int_pair_t *pairs;
} info_t;
``````

Given a maximum of 1000 characters per line, and assuming a one character string followed by a space, followed by a single digit `Zinteger`, 332 is the greatest number of pairs (single digit followed by space followed by a single digit) that could be accommodated in the remaining characters.

So you could use a fixed size array of `int_pair_t pairs[332]` into which the pairs from one line are read, as well as a string for the `term`, and `int`s for the `Zinteger` and pair count. Once you have read the line, you can copy the pairs data into a newly malloced `info_t` struct of precisely the right size, and add that to whatever collection you have for the lines.

If you don't overly care about memory usage (it's less than 3KB per line), you can skip the malloc and copy, and just allocate a fixed sized array in the `info_t` struct:

``````#define MAX_PAIRS    332

typedef struct {
char term[1000];
int zinteger;    /* so named to avoid confusion */
int n_pairs;
int_pair_t pairs[MAX_PAIRS];
} info_t;
``````

Your original question also asked how to read the data in from a text file. Read a line of data from the file into a `char` buffer. Then you can use `strtok()` to process the fields from the file using space as a delimiter. You can combine that with `sscanf()` to extract the first 2 fields if you want, and the process the remaining fields with `strtok`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download