-3

currently, I am writing code in c program for printing small portion of contents from the input file. Actually, in my code I can able to print just one single line. but, i have to print next 5 lines after that one line.

I am new to programming, please help to solve this problem** code is given below

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int lineNumber = 2;

int main()
{
   FILE *file;
   char line[100];
   int count = 0;

   ///Open LS-dyna file to read
    file = fopen("P:\\tut_c\\read\\df-read\\in.txt", "r");
    if (file == NULL)
    {
        perror("fopen");
        exit(EXIT_FAILURE);
    }

    else if ( file != NULL )
    {
        char line[256];
        while (fgets(line, sizeof line, file) != NULL)
        {
            if (count == lineNumber)
            {
            printf("\n str %s ", line);
            fclose(file);
            return 0;

            }
            else
            {
                count++;
            }
        }
        fclose(file);
    }
return 0;

}
BoBTFish
  • 19,167
  • 3
  • 49
  • 76
prasath
  • 23
  • 6
  • I removed the C++ tag. C and C++ and completely different languages. If you want to do this in C++, it is much simpler. – BoBTFish Apr 13 '17 at 06:11

1 Answers1

1

The first logical error occurs in your while loop, first iteration, when you close the file and return 0.

Next, there is no reason to have a counter for your lines, since there are many c functions that can handle finding the end of file (eof).

Instead:

  1. Use a while loop for iteration through the file.
  2. Use a standard library c function for file reading.
  3. Check if file has reached the end.
  4. If the line is still valid, then print the line.

Here is some code to reiterate:

int main()
{
   FILE *file;
   file = fopen("file.txt", "r");

   if (!file){ // check if file exists
       perror("fopen"); 
       exit(EXIT_FAILURE);
    }
    else { // if file exists, then...

       char line[256];
       while(fgets(line, sizeof line, file)){ 
           printf("\n str %s ", line);
       }

       fclose(file);
    }

return 0;
}// end main
Nick Meyer
  • 181
  • 6
  • 2
    Please see [Why is `while(!feof(file))` always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – unwind Apr 13 '17 at 09:53
  • 1
    Thank you so much for that! For some reason, my university professors never mentioned that to me, and I was never aware that was an incorrect usage of feof()! – Nick Meyer Apr 13 '17 at 22:45