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

Citation

Click to select citation style

Shovon, A. R. (2019, September 29). Read File by N Lines using C programming language. Ahmedur Rahman Shovon. Retrieved June 22, 2024, from https://arshovon.com/blog/read-file-by-n-lines/

Shovon, Ahmedur Rahman. “Read File by N Lines using C programming language.” Ahmedur Rahman Shovon, 29 Sep. 2019. Web. 22 Jun. 2024. https://arshovon.com/blog/read-file-by-n-lines/.

@misc{ shovon_2019,
    author = "Shovon, Ahmedur Rahman",
    title = "Read File by N Lines using C programming language",
    year = "2019",
    url = "https://arshovon.com/blog/read-file-by-n-lines/",
    note = "[Online; accessed 22-June-2024]"
}
Read File by N Lines using C programming language