Edited, because if the file being read did not end with a line break ( '\n'
), the last character would be deleted. Placed a test to verify that the last character of the read line is '\n'
before replacing.
As user72726 explained in his response, the fgets function includes the line feed when reading from file ( '\n'
). At first I thought about inserting the semicolon when reading the file, but this limits some other treatment you might want to do.
I suggest taking this line feed when reading from the file
while (fgets(linha1,255,file)!=NULL) {
linha *l1 =(linha*) malloc(sizeof(linha));
if (linha1[strlen(linha1) - 1] == '\n') // testa se o último caractere é \n
linha1[strlen(linha1) - 1] = 'while (current != NULL) {
printf("- %s;\n",current->produtos);
current = current->prev;
}
'; // troca o \n pelo char null
l1->produtos =(char*) malloc(strlen(linha1)+1);
strcpy(l1->produtos,linha1);
l1->prev = tail;
tail = l1;
}
and then add the semicolon and line feed when displaying on the screen
while (fgets(linha1,255,file)!=NULL) {
linha *l1 =(linha*) malloc(sizeof(linha));
if (linha1[strlen(linha1) - 1] == '\n') // testa se o último caractere é \n
linha1[strlen(linha1) - 1] = 'while (current != NULL) {
printf("- %s;\n",current->produtos);
current = current->prev;
}
'; // troca o \n pelo char null
l1->produtos =(char*) malloc(strlen(linha1)+1);
strcpy(l1->produtos,linha1);
l1->prev = tail;
tail = l1;
}
It works because functions that handle strings stop when they find a null character - see ref. of the strcpy of the link below, at the end of the first sentence "including the terminating null character (and stopping at that point)".
Note that if you do sizeof(linha1)
will be different from strlen(linha1)
, normal, if I'm not mistaken, it's the difference being 1 but here it will be 2 because linha1
is a pointer that in the end has two null characters instead of 1, which strlen does not count.
The above paragraph is incorrect because sizeof(linha1)
in the case of this program will always be 255, since it is the size allotted in the declaration.
One important thing, though out of the question, is releasing all the memory you use. So, if it were me, for each malloc I'd put a memfree in the program even though the program would close right after.
References (other functions appear in the menu on the left):
link
link