nightk nightk - 1 year ago 97
C Question

Read each line in a text file when I press a key? C programming

I know how to use fgets inside a while loop to read an entire text file, but how can I press a key inside that loop, so it will read another line, one at a time?

I tried with a simple printf("Press any key\n") getchar() but nothing happens, I run the programm and it just doesn't do anything, not even show the first line. I'm assuming this may be a stupid question but I can't find how to do this :(

Here is what I've tried:

/* gcc readline.c -Wall -o read */

#include <stdio.h>
//#include <stdlib.h>

int main (int argc, char *argv[]) {

char url[]="dbus.log";
FILE *arq;
char info[1000];

arq = fopen(url, "r");

while (fgets(info, sizeof(info), arq) != NULL) {
printf("%s", info);
printf("Press Any Key to Continue\n");

return 0;

Answer Source

The program isn't showing the prompts because stdio is buffered and you're not flushing. Use fflush(stdout); to ensure that buffered output is produced.

Like this:


Also note that by default stdin is in "cooked" IO mode. Pressing enter will produce a character, but other characters will be buffered until enter is pressed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download