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:

alt Program output of Read File by N Lines

Advertisement

Cite This Work
APA Style
Shovon, A. R. (2019, September 29). Read File by N Lines using C programming language. Ahmedur Rahman Shovon. Retrieved March 29, 2024, from https://arshovon.com/snippets/read-file-by-n-lines/
MLA Style
Shovon, Ahmedur Rahman. “Read File by N Lines using C programming language.” Ahmedur Rahman Shovon, 29 Sep. 2019. Web. 29 Mar. 2024. https://arshovon.com/snippets/read-file-by-n-lines/.
BibTeX entry
@misc{ shovon_2019,
    author = "Shovon, Ahmedur Rahman",
    title = "Read File by N Lines using C programming language",
    year = "2019",
    url = "https://arshovon.com/snippets/read-file-by-n-lines/",
    note = "[Online; accessed 29-March-2024; URL: https://arshovon.com/snippets/read-file-by-n-lines/]"
}
Previous Post

8-diamond