0

I'm currently working on making a program that reads this text file (translated from Italian) and store a line in a single-linked list. But I have to ignore comments. Comments starts with '#'. In my list's nodes, I must have ingredient, simbol and quantity, without comments.

Input file:

#ingredients for donut
milk    l   0.25
flour   g   300
oil     l   0.05 # a spoon
eggs    u   2
butter  g   50
yogurt  g   50 # white yogurt
# enjoy your meal



struct nodo {
  char ingredient[15];
  char simbol[2];
  float quantity;
  struct nodo * next;
};

I tried some codes, now i'm stuck on this (read function):

struct nodo * read (struct nodo * top) {
FILE *fp;
fp = fopen("ingredients.txt", "r");

char comment[30];
char comm;

while(!feof(fp)) {
    
    fscanf(fp, "%c", &comm);
    
    if(comm == '#') {
        fgets(comment, 30, fp);
    }
        
    struct nodo * new = CreaNodo();
    fscanf(fp, "%s%s%f", new->ingredient, new->simbol, &new->quantity);
        
  if(!top) top = new;
  else {
        new->next = top;
        top = new;
     }
  }

fclose(fp);
return top;
}
Luigi V.
  • 79
  • 7
  • since you are not specific in what is not working: Always check return value from runtime functions e.g. fopen can fail. Never read from a file check for feof, instead try to read from the file `while (fgets(comment,sizeof(comment),fp)!=NULL) {..}` – AndersK Sep 27 '20 at 14:47
  • https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – William Pursell Sep 27 '20 at 15:31

1 Answers1

0

The second fscanf has not the first char of a non-comment line (it is lost in the comm variable).

fgets()'ing every line then searching for '#' in that line and sscanf()'ing the line if not found is easier (my opinion) and probably more I/O efficient.