I want to read lines from a file line-by-line, but it's not working for me.
Here is what I tried to do:
FILE *file;
char *line = NULL;
int len = 0;
char read;
file=fopen(argv[1], "r");
if (file == NULL)
return 1;
while ((read = getline(&line, len, file)) != -1) {
printf("Retrieved line of length %s :\n", &read);
printf("%s", line);
}
if (line)
free(line);
return 0;
Any suggestions why that isn't working?
To get it to work correctly, there's a few changes.
Change int len
to size_t len
for the correct type.
getline()
syntax is incorrect. It should be:
while ((read = getline(&line, &len, file)) != -1) {
And the printf
line should also be modified, to print the number returned instead of a char
and string interpretation:
printf("Retrieved line of length %d:\n", read);
Alternatively you can also use this code. It will read the whole file line by line and print those lines.
char buf[1000];
ptr_file =fopen("input3.txt","r");
if (!ptr_file)
return 1;
while (fgets(buf,1000, ptr_file)!=NULL)
printf("%s",buf);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With