7

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?

yulian
  • 1,555
  • 3
  • 20
  • 48
KaramJaber
  • 777
  • 5
  • 11
  • 22

3 Answers3

5

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);
Leigh
  • 11,344
  • 4
  • 27
  • 35
  • 1
    Note `read` should be type `ssize_t` and not `char`. 2 problems:`char` may be `unsigned char` and never == -1 and `char` is not the same range as `ssize_t`. The `printf()` format specifier is a bit of a problem too. Suggest: `printf("Retrieved line of length %lld:\n", (long long) read);` – chux - Reinstate Monica Apr 06 '15 at 21:44
4

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);
user3651854
  • 124
  • 1
  • 8
3

Your second argument to getline() is (very) wrong.

It should be size_t *, you're passing int. You should have received compiler warnings for this problem.

Make it:

size_t len;

and in the call:

getline(&line, &len, file)

Also the return value is of type ssize_t, not char.

You should really read the manual page for getline() and make sure you understand it, before writing code to use the function.

unwind
  • 378,987
  • 63
  • 458
  • 590