tibsar - 2 months ago 18

C Question

I can give my program input files such as the following:

`1 0 0 0 2 -1`

16 70 -169 -580 75

1 0 4 0 -5

0 -9 3 5 -3

5 -4 3 -2 0

1.0 -3.4 5.4531 -4.2077 1.5092 -0.2030

Each of these lines represents a polynomial. For instance, the first line represents

`x^6 + 2x^2 - 1`

I am trying to read in this file but am not sure how to deal with the tabs and new lines. I am also not sure how to handle the fact that the amount of coefficients and polynomials can change.

Right now I have:

`polynomial** readPolyFile(FILE *polyFile){`

polynomial *p = NULL;

int size = 1; /* Size to malloc */

polynomial **polynomials = NULL;

polyList = malloc(sizeof(polynomial*) * size); /* Initialize */

if(polyList == NULL){

fprintf(stderr, "%s %n: Could not allocate memory\n", __FILE__, __LINE__);

exit(-99);

}

/* Read all of the data from the file */

do {

}

}

My initial thought is to increment the size each time I need to, but I'm not sure if that's the best way to go about this.

My definition of

`polynomial`

`typedef struct`

{

unsigned int nterms; /* number of terms */

double complex *polyCoef; /* coefficients */

} polynomial;

I would like to return a list of polynomial structs. Any suggestions on how to go about this?

Answer

Any suggestions on how to go about this?

Read inputs into a linked list and then form the array when done.

Some quick code, lacking needed error checking, to get you started.

Set up an empty linked-list

```
typedef struct LL {
polynomial *poly;
struct LL *next;
} LL;
LL head = { NULL, NULL };
LL *p = &head;
```

Inside the loop, read a line in the a buffer, parse it to a `polynomial`

and append to the LL.

```
#define N 1000
count = 0;
char buf[N];
/* Read all of the data from the file */
while (fgets(buf, sizeof buf, polyFile)) {
p->next = malloc(sizeof *(p->next));
p = p->next;
// TBD code for OP.
// Hint: degree of polynomial < sizeof buf/2
p->poly = polyList_from_line(buffer);
p->next = NULL;
count++;
}
```

Allocate for the array

```
polyList = malloc(sizeof *polyList * count);
p = head.next;
for (i=0; i< count; i++) {
assert(p);
polylist[i] = p->poly;
next = p->next;
free(p);
p = next;
}
return polylist;
```

Sub problem: More pseudo code to read tab separated data

```
polynomial *polyList_from_line(char *buffer) {
double complex coef[some factor of N];
count = 0;
char *token = strtok(buffer, "\t");
while (token) {
// parse the token for a complex number
if (sscanf(buffer, tbd_format, tbd_variables) != expected_result)
break;
coef[count++] = ...
token = strtok(tbd_code);
}
// Malloc polynomial using count
// Populate polynomial from coef[]
// return allocation
}
```