Why do you open the file twice (and close it only once even when opening fails)?
You should have a look at the
rewind - C++ Reference[
^] function.
To speed up execution you can also allocate a ring buffer with
m
items to store the line positions. Then you can use
fseek - C++ Reference[
^] with the lowest position to jump to the first line to be printed out.
Untested snippet:
long int *positions = (long int *)malloc(m * sizeof(long int));
int pos = 0;
int last_pos = 0;
positions[0] = 0;
while (fgets(line, 199, file_name1) != NULL)
{
if (++pos >= m)
pos = 0;
positions[pos] = ftell(file_name1);
last_pos = pos;
count++;
}
if (count < m || ++last_pos >= m)
last_pos = 0;
fseek(file_name1, positions[last_pos], SEEK_SET);
while (fgets(line, 199, file_name1) != NULL)
{
printf("%s",line);
}
free(positions);