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,601
  • 3
  • 21
  • 49
KaramJaber
  • 851
  • 5
  • 13
  • 24
  • 1
    2 mistakes ... 1:- line is just a pointer, that pointer needs to point to some malloced memory .... 2:- len = 0, why do want to read 0 bytes???? .. google for a "simple file operation program in c" ... – Deepthought Nov 06 '13 at 14:00
  • 2
    @Deepthought No, that's not how `getline()` works. It allocates memory for the line itself. –  Nov 06 '13 at 14:01
  • 2
    Straight example at [man getline](http://linux.die.net/man/3/getline). – Sunil Bojanapally Nov 06 '13 at 14:01
  • 1
    Possible duplicate of [C read file line by line](https://stackoverflow.com/questions/3501338/c-read-file-line-by-line) – Ciro Santilli OurBigBook.com Nov 24 '17 at 16:38
  • Your compiler should have told you that the second argument to `getline` is wrong. It expects a pointer and not an integer. – Jens Gustedt Nov 24 '17 at 21:31

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
  • 12,038
  • 4
  • 28
  • 36
  • 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
  • 391,730
  • 64
  • 469
  • 606