954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Reading specific line

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

BoB3R
Newbie Poster
16 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

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

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

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

gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

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

BoB3R
Newbie Poster
16 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

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

BoB3R
Newbie Poster
16 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 
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;
*/
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: