how to restore the position of a file pointer

K

Kevin Zhou

I have a file that contains 22 lines, each line has two float separated
by a space.
I want to store those float data into a two-dimensional array which size
I want the program to determine at run time
so i wrote the following function to count the number of lines in the
file to determine the row size for my storage array

int countline(FILE *fp)
{
int count;
count=0;
while( (c=fgetc(fp))!=EOF){
if (c == '\n')
++lcount;
}
return lcount;
}
I know that the file pointer foward one character each time fgetc is called
Is there a way to restore the position of the file pointer to the
beginning of the file
without fclose() and fopen() the file again?
 
T

those who know me have no need of my name

in comp.lang.c i read:
Is there a way to restore the position of the file pointer to the
beginning of the file without fclose() and fopen() the file again?

rewind
 
R

Régis Troadec

"Kevin Zhou" <[email protected]> a écrit dans le message de

Hi,

[snipped]
I know that the file pointer foward one character each time fgetc is called
Is there a way to restore the position of the file pointer to the
beginning of the file
without fclose() and fopen() the file again?

Use the functions fseek() or rewind() (in stdio.h). Perhaps this point is a
FAQ, so I invite you to read it.

e.g:

---- try.txt ----
This is the first line of this sample file ...
Here is the second line
Here is the third line
and so forth...

---- exple.c ----
#include <stdio.h>
#include <stdlib.h>

int main(void)
{

int c, retcode = EXIT_SUCCESS;
FILE * fic = fopen("try.txt", "r");

if (fic)
{
while ((c=fgetc(fic))!= EOF)
putchar(c);

putchar('\n');

rewind(fic);
/* fseek(fic, 0L, SEEK_SET); */

while ((c=fgetc(fic))!= EOF)
putchar(c);

fclose(fic);
}
else
{
fprintf(stderr,"Coudn't open try.txt\n");
retcode = EXIT_FAILURE;
}

return retcode;
}

It should output the content of try.txt twice.


Regis.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,539
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top