The following program is supposed to read a particular text file and print its contents line by line. However, it results in an infinite loop. Why?
#define __STDC_WANT_LIB_EXT2__ 1
#include <stdio.h>
int main(void)
{
char *line = NULL;
size_t buf_len;
size_t line_len;
FILE *fp = fopen("README.txt", "r");
while (1) {
line_len = getline(&line, &buf_len, fp);
if (line_len < 0)
break;
printf("%s", line);
}
return 0;
}
I noticed that I could fix the problem by changing line_len < 0 to line_len == -1, but I don't understand the reason why this fixes the problem. Isn't -1 less than 0?
(C compiler: gcc 9.4.0 on Ubuntu 20.04).