Reputation: 103
I'm a beginner in C and I'm trying to create a simple todo list program. I'm trying to use getline in a while loop, as I saw on another stack overflow answer and I thought I understood it but it's just creating an infinite loop. Also it seems to be skipping the first word for some reason. Here is my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE *list;
int i = 0;
int item = 0;
char items[10];
char chars[1000];
char * line = NULL;
size_t len = 0;
ssize_t read;
int main() {
list = fopen("/Users/bendavies/Documents/C/list.txt", "r");
int letterCount = fscanf(list,"%s",chars);
printf("Welcome to the to-do list. It can hold up to 10 items.\n");
printf("%d\n", letterCount);
if (letterCount == -1) {
printf("The list currently has no items!\n");
} else {
while ((read = getline(&line, &len, list)) != 1) {
item += 1;
printf("%d. %s", item, line);
}
}
fclose(list);
return 0;
}
The output I'm currently getting with the following list.txt:
Eat food
Drink water
Breath air
Is:
1. food
2. Drink water
3. Breath air
4. 18446744073709551615
5. 18446744073709551615
and so on and so forth.
Thank you in advance! :)
Upvotes: 1
Views: 3719
Reputation: 3985
but it's just creating an infinite loop.
This line of your code: while ((read = getline(&line, &len, list)) != 1)
Unless a line contains 1
character (just a newline), it will be an infinite loop. The POSIX getline()
function will return -1
(not EOF
, even though EOF
is usually -1) when the file is completely read. So change that line to:
while ((read = getline(&line, &len, list)) != -1)
But, I don't see you using the value of read
inside that loop, so this would be better:
while (getline(&line, &len, list) != -1)
And inside that loop, I see: printf("%d. %s", item, line);
You might find very old implementations of getline()
that don't include the newline, in which case, if you want your output in separate lines, you need to put a \n
:
printf("%d. %s\n", item, line);
However, if you use a more modern implementation, it will preserve the newline in accordance with the POSIX specification.
Also, if the very last 'line' in the file is not terminated with a newline, you might still want to add one. In that case, you could keep the read length and use that to detect whether there is a newline at the end of the line.
Also it seems to be skipping the first word for some reason
Because of int letterCount = fscanf(list,"%s",chars);
That fscanf
reads the first word of your file. Now the file pointer is at that position (end of the first word) and further reading of the file will happen from that place.
So, reposition the file pointer to the beginning of the file after reading the first word from the file:
Fix 3:
int letterCount = fscanf(list,"%s",chars);
fseek(list, 0, SEEK_SET); // <-- this will reposition the file pointer as required
Upvotes: 4