I have created 2 functions that read some data from a file and write the data in another file, but using linked lists and dynamically allocated strings in that list, but I have a logic error that I can't find:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct product {
char id[6];
char *name;
int price;
struct product *next;
};
struct product *read(struct product *head, FILE *input) {
struct product *p, *q, *aux;
p = (struct product *)malloc(sizeof(struct product));
char aux_id[6];
char aux_name[20];
int aux_price;
fscanf(input, "%s %s %d", aux_id, aux_name, &aux_price);
strcpy(p->id, aux_id);
p->name = (char *)malloc(strlen(aux_name) * (sizeof(char)));
strcpy(p->name,aux_name);
p->price = aux_price;
p->next = NULL;
head = p;
while (fscanf(input, "%s %s %d", aux_id, aux_name, &aux_price) != EOF) {
q = (struct product *)malloc(sizeof(struct product));
q->name = (char *)malloc(strlen(aux_name) * (sizeof(char)));
q->next = NULL;
strcpy(q->name, aux_name);
strcpy(q->id, aux_id);
q->price = aux_price;
p->next = q;
p = q;
}
return head;
}
void write(struct product *head, FILE *output) {
struct product *p;
p = head;
while (p != NULL) {
fprintf(output, "%s %s %d\n", p->id, p->name, p->price);
p = p->next;
}
}
int main() {
struct product *head, *p, *q;
FILE *input = fopen("input.txt", "r+");
FILE *output = fopen("output.txt", "w+");
head = read(head, input);
write(head, output);
fclose(input);
fclose(output);
}
input file looks like this:
333444 Cola 3
332312 Pepsi 4
123451 Mountain 3
output file looks like this
333444 Cola 3
332312°)q 4
123451à)q 3
malloc( strlen(...))does not allocate memory for the terminating null character. Why don't you usestrdupinstead ofmalloc+strcpy? And why are you duplicating so much code inread? Last but not least: where is you error checking, especially forfscanf?char *nametochar name[20]instruct product? Then you wouldn't need to allocate memory forq->namemanually.strdupis not a function in the C standard library (it's posix).