somebody somebody - 4 months ago 26
C Question

How to read a line from a file in C

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)

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);