Hello,
I am trying to do a program that is reading for example a.txt file that have 5 lines and i want him to show me for example line #3 only, i know i need to use fgets but i rly dont know how to start it
a.txt

1;27.01.1957;8;12;31;39;43;45;
2;03.02.1957;5;10;11;22;25;27;
3;10.02.1957;18;19;20;26;45;49;
4;17.02.1957;2;11;14;37;40;45;
5;24.02.1957;8;10;15;35;39;49;

Thanks for help

Recommended Answers

All 5 Replies

Read and discard lines 1 and 2, then read line 3 and you've got it.

I would open the file and read three lines into it and then display the results...This sounds like a for loop to me..

Hello,
Hmm but what if Ive got like 7k of lines is there any difference?
I will try to show you some code in sec

Hello,
Ive got something like that to show all the lines any help in it?

#include <stdio.h>

int main ()
{
FILE *f;
   f = fopen ( "a.txt", "r" );
   if ( f != NULL )
   {
      char line [ 128 ];

      while ( fgets ( line, sizeof line, f ) != NULL ) 
      {
         fputs ( line, stdout );
      }
      fclose (f);
   }
   else
   {
      perror ( "a.txt" );
   }
   system("pause");
}

Sorry for one post after another

Read and discard lines 1 and 2, then read line 3 and you've got it.

As in...

#include <stdio.h>

void fetch(const char *filename, int lineno)
{
   char line [ 128 ];
   int i;
   FILE *file = fopen ( filename, "r" );
   if ( file )
   {
      for ( i = 0; i < lineno; ++i )
      {
         if ( fgets ( line, sizeof line, file ) == NULL )
         {
            return;
         }
      }
      fputs ( line, stdout );
      fclose ( file );
   }
   else
   {
      perror ( filename );
   }
}

int main ()
{
   fetch ( "a.txt", 3 );
   return 0;
}

/* a.txt
1;27.01.1957;8;12;31;39;43;45;
2;03.02.1957;5;10;11;22;25;27;
3;10.02.1957;18;19;20;26;45;49;
4;17.02.1957;2;11;14;37;40;45;
5;24.02.1957;8;10;15;35;39;49;
*/

/* my output
3;10.02.1957;18;19;20;26;45;49;
*/
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.