1

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.

Ankit R Gadiya
  • 449
  • 1
  • 7
  • 14

1 Answers1

2

the issue is that there's a remaining linefeed from your first scanf("%s", file); statement that is picked up by your getchar() the first time, so the loop runs twice without any user input.

To prevent that, just getchar() before your loop.

Aside (as comments noted), fgets (buffer, 80, in) needs buffer[80] only.

And scanf("%s", file); could be protected like scanf("%80s", file); (here you need to keep 81 bytes, unlike in fgets)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • If scanf call is the problem then why is it happening everything the loop iterates. Each consecutive time the for loop runs it iterates twice as many times not just the first time. Also, about the getchar() call, i cannot place it before the loop as the problem wants me to first print 20 lines and then prompt user for input, if the user enter 'q', then the program should stop, any other input should result in printing the next 20 lines. – Ankit R Gadiya Aug 17 '17 at 16:48
  • 1
    Because you have `getchar` in the loop. You enter a character that is not `'q'` not just a plain `Enter`? Then there will a newline in the input buffer. – Weather Vane Aug 17 '17 at 16:52
  • Okay i got it, I tried hardcoding the file name and thus removing the scanf call and it worked. Obviously not the correct idea though. Thanks – Ankit R Gadiya Aug 17 '17 at 17:00