Read a file by n
lines while user pressing y
until end of file.
/*
Author: Ahmedur Rahman Shovon
License: "GPL"
Date: 2019/09/29
*/
#include <stdio.h>
/* Function that prints a line from file. Update the printf contents to change format. */
void print_line(int line_number, char line[])
{
printf("%s", line);
}
int main()
{
char filename[] = "data.txt";
FILE *file = fopen(filename, "r");
int i = 1;
// Number of lines per chunk
int n = 3;
int end = n;
char user_choice;
if ( file != NULL )
{
char line[1000]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file) != NULL) /* read a line */
{
if(i<=end)
{
print_line(i, line);
}
else
{
printf("Do you want to continue? Press 'y' to continue or any other key to exit: ");
// The begining space is to ignore the enter key press
scanf(" %c", &user_choice);
if(user_choice == 'y')
{
print_line(i, line);
end = end + n;
}
else
{
printf("You pressed '%c'\n", user_choice);
break;
}
}
i++;
}
fclose(file);
}
else
{
printf("Error in reading file");
}
return 0;
}
data.txt
:
This is line number 1 with some dummy characters
This is line number 2 with some dummy characters
This is line number 3 with some dummy characters
This is line number 4 with some dummy characters
This is line number 5 with some dummy characters
This is line number 6 with some dummy characters
This is line number 7 with some dummy characters
This is line number 8 with some dummy characters
This is line number 9 with some dummy characters
This is line number 10 with some dummy characters
This is line number 11 with some dummy characters
This is line number 12 with some dummy characters
This is line number 13 with some dummy characters
Output:
Advertisement