I'm writing a C program which prompts user for a file name and when entered it shows first 20 lines and then wait for the input from user. So, everything worked fine just that it showed 40 lines instead of 20, so I reduced the number of lines to 1 and it showed 2 lines instead. I even tried with while loop instead of for loop but still same result.
#include <stdio.h>
int main (void)
{
FILE *in;
char file[81], buffer[81];
int flag = 1, c, i;
printf("File: ");
scanf("%s", file);
if ((in = fopen (file, "r")) == NULL) {
printf("Unable to open the file: %s\n", file);
return 1;
}
while (flag) {
for (i = 0; i < 1; i++) {
if (fgets (buffer, 80, in) != NULL) {
printf("%s", buffer);
} else {
flag = 0;
}
}
c = getchar();
if (c == (char) 'q')
flag = 0;
}
fclose (in);
return 0;
}
Problem in C by Stephen G Kochan, Chapter 16, Problem 6
Note: I'm not expecting an alternative method to solve the problem, I just want to know what is causing this problem.