Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getline startover

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++;   
    }
}
like image 797
JupiterOrange Avatar asked Jan 28 '13 21:01

JupiterOrange


1 Answers

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

rewind(fp);

to start at the beginning of the stream again.

like image 151
Eric J. Avatar answered Oct 12 '22 23:10

Eric J.