Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

file

getline

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?

like image 904
KaramJaber Avatar asked Nov 06 '13 13:11

KaramJaber


2 Answers

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);
like image 98
Leigh Avatar answered Oct 16 '22 11:10

Leigh


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);
like image 40
user3651854 Avatar answered Oct 16 '22 12:10

user3651854