How to read a line from a file in C [closed]
Asked Answered
P

3

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?

Photoreceptor answered 6/11, 2013 at 13:55 Comment(5)
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" ...Liberate
@Liberate No, that's not how getline() works. It allocates memory for the line itself.Ivonne
Straight example at man getline.Jewelfish
Possible duplicate of C read file line by lineManstopper
Your compiler should have told you that the second argument to getline is wrong. It expects a pointer and not an integer.Cookgeneral
S
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);
Sumerlin answered 6/11, 2013 at 14:6 Comment(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);Lonergan
M
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);
Mean answered 1/4, 2015 at 17:21 Comment(0)
C
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.

Cottingham answered 6/11, 2013 at 13:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.