This might help you out:
Code:
#include <stdio.h>
#define MAXLINE 127
#define TRUE 1
#define FALSE 0
int main(int argc, char **argv)
{
FILE *fp;
char text_buf[80];
char reply;
int lineno = 1;
int show_line_numbers;
if ((fp = fopen(argv[1], "r")) == NULL)
{
fprintf(stderr, "ERROR: Can't open file! Exiting...\n");
return -1;
}
printf("Print line numbers? (Y/N): ");
scanf(" %c", &reply);
if (reply == 'Y')
show_line_numbers = TRUE;
else if (reply == 'N')
show_line_numbers = FALSE;
else
{
printf("Invalid Option!\n");
return -1;
}
while (fgets(text_buf, MAXLINE, fp))
{
if (show_line_numbers)
printf("%-4d: %s", lineno, text_buf);
else
printf("%s", text_buf);
lineno++;
if (lineno % 20 == 0)
{
printf("Continue? (C/Q): ");
scanf(" %c", &reply);
if (reply == 'C')
continue;
else if (reply == 'Q')
break;
}
}
return 0;
}
Three notes:
1.) For the problem of printing line numbers only when you choose: in this program we're going to show the line anyway, hence lines 38-41, the trick is to use a separate variable to test whether we should be showing line numbers.
2.) You'll notice that in the scanf call when i read in the value for reply, there's a space before the character conversion and the reason for this is the way that scanf reads input, if you leave it out it there will be problems because when you enter a choice, you also unknowingly enter a newline into the standard input stream.
3.) In the fopen call i used "argv[1]". This is the first command line parameter supplied to the program. so to use this program just call it with a filename on the command line e.g. "program_name any_file_name" without quotes. This makes the program more general so you can use it on any text file.
best of luck.