getline startover
Asked Answered
D

2

5

I'm using the get line function in C to read through the lines of a file. I want to loop over the function so that I can read through the file n number of times. For some reason though, it only reads through it once (I think there's a pointer somewhere still pointing to the last line) at the beginning of the subsequent loops. How do I get it to reset?

To make things clearer, if there were 100 lines in the file, below, the largest val would get would be 100 even though it should get up to 300.

Thanks!

FILE* fp = myfopen (inf, "r");
char* line = NULL;
size_t len = 0;

int num=3
int val=0

for (i=0;i<num;i++)
{
    while (getline (&line, &len, fp) != -1)
    {  
        val++;   
    }
}
Deen answered 28/1, 2013 at 21:48 Comment(0)
C
7

Once you read past the end of the file, you have to call

rewind(fp);

to start at the beginning of the stream again.

Copyedit answered 28/1, 2013 at 21:50 Comment(1)
Or ftell for a little more control...but rewind is more clear.Virnelli
S
0

As mentioned you can use the rewind() function to start over again, the other option is of course to move the open/close of the file into your loop:

FILE* fp; = myfopen (inf, "r");

for (i=0;i<num;i++)
{
    fp = myfopen(inf, "r");
    while (getline (&line, &len, fp) != -1)
    {  
        val++;   
    }
    fclose(fp);
}
Senary answered 28/1, 2013 at 22:23 Comment(2)
Opening and closing files repeatedly causes a bunch of unnecessary churn in the kernel (even if a lot of data structures are cached, it's still syscalls).Virnelli
@Virnelli - Didn't say it was a good solution, just that it's another solution. Depending on the application better still could be reading out the whole file then manipulating the data as need be from a local variableSenary

© 2022 - 2024 — McMap. All rights reserved.