dimanche 19 novembre 2017

to read n random lines from file in c

Need to print n random lines from a file

and whenever i run the code it only printing the first random line

Where did i do wrong?

Thanks in advance

   #include<stdio.h>
   #include<stdbool.h>
   #include<time.h>
   int main()
 {
 FILE* file=fopen("questionbank.txt","r");
   if(NULL==file)
    {
      fprintf(stderr,"cannot open file");
        return 1;
     }
     size_t buffer_size=80;
     char *buffer=malloc(buffer_size * sizeof(char));

     int n=10,i;
   bool arr[300]={0};
    time_t t;
 srand((unsigned)time(&t));
 for(i=0;i<n;++i)
 {
  int r=rand()%301;
  if(!arr[r]&& r%6==0)
  {
    while(fgets(buffer,buffer_size,file))
    {
       if(flag==r)
        printf("%s",buffer);
        flag++;
   }
 }
  else
  i--;
  arr[r]=1; 

 }
  }




Aucun commentaire:

Enregistrer un commentaire