0

The code I have only prints the first x lines. I really appreciate if you can give me some pointers on what I am missing,

#include <stdio.h>
int main ( void )
{
    static const char filename[] = "testfile.txt";

    int lineNumbers[] = {1,2};
    size_t numElements = sizeof(lineNumbers)/sizeof(lineNumbers[0]);
    size_t currentIndex = 0;

    FILE *file = fopen ( filename, "r" );
    int i =0;
    if ( file != NULL )
    {
        char line [ 328 ]; /* or other suitable maximum line size */
        while ( fgets ( line, sizeof line, file ) != NULL )
        { /* read a line */
            i++;
            if (i  == lineNumbers[currentIndex])
            {
                fputs( line, stdout ); /* write the line */
                if (++currentIndex == numElements)
                {
                    break;
                }
            }
        }
    fclose ( file );
}
Samun
  • 151
  • 1
  • 1
  • 12
  • Re "*I really appreciate if you can give me some pointers on what i am missing*", A description of what you are trying to do. – ikegami May 10 '18 at 05:02
  • 2
    Loop continually reading as you do with `fgets`. Keep a `read` flag (`0/X`) and line counter. `if (count % y == 0) read = X; if (X) { X--; /* store line */ }` – David C. Rankin May 10 '18 at 05:07
  • thank you so much . this one line fix saved me a lot. I was about to store each line in an array. – Samun May 10 '18 at 05:08

1 Answers1

1

Use extra fgets to skip the lines you don't want.
Given x = 2, y = 3 and the input file:

1 read me
2 read me
3 dont read me
4 dont read me
5 dont read me
6 read me 
7 read me
8 dont read me
9 dont read me
10 dont read me
11 read me 
12 read me

the following program:

#include <stdio.h>
int main ( void )
{
    static const char filename[] = "testfile.txt";

    int x = 2;
    int y = 3;
    size_t currentIndex = 0;

    FILE *file = fopen(filename, "r");
    char line [ 328 ]; /* or other suitable maximum line size */

    // until the end of file
    int linenumber = 0;
    while(!feof(file)) {
        // read x lines
        for(int i = x; i; --i) {
            if (fgets(line, sizeof(line), file) == NULL) break;
            ++linenumber;
            // and print them
            printf("READ %d line containing: %s", linenumber, line);
        }
        // skip y lines
        for(int i = y; i; --i) { 
            // by reading a line...
            if (fgets(line, sizeof(line), file) == NULL) break;
            ++linenumber;
            // and discarding output
        }
    }
    fclose(file);
}

produces the following output:

READ 1 line containing:     1 read me
READ 2 line containing:     2 read me
READ 6 line containing:     6 read me 
READ 7 line containing:     7 read me
READ 11 line containing:     11 read me 
READ 12 line containing:     12 read me
KamilCuk
  • 120,984
  • 8
  • 59
  • 111