简体   繁体   中英

Open multiple files using single file pointer

Can I open multiple file using a single file pointer in one loop?. I have an array of strings which contains 50 file names.It shows only one file name, then segmentation fault occur. Please suggest.

int main()
{
  DIR *dir;
 struct dirent *pq;
 char f_name[40];
 const char *buffer[2000],*buffer1[2000];
 int count=0;
 if ((dir = opendir ("/home/student/storage")) != NULL)
  {
  /* print all the files and directories within directory */
  while ((pq = readdir (dir)) != NULL)
     {
       buffer[count]=pq->d_name;
       //printf("%s\n",pq->d_name);
       count++;
     }
  closedir (dir);
  }
 else
    {
  /* could not open directory */
    perror ("");
    return EXIT_FAILURE;
    }
 /*creating file name and removing unwanted names*/
 FILE *gh;
  char *s;
 int total=0,i;
   for(i=0;i<count;i++)
     {
      s = strstr(buffer[i],".txt");
      if (s !=NULL)
      {
       printf("%s\n",buffer[i]);
       buffer1[total]=buffer[i];//buffer1 contains all the required file name
       sprintf(f_name,"/home/student/storage/%s",buffer1[i]);
       //gh=fopen(f_name,"r");
       //data[total]=read(gh,data[i]);
       total++;
       //fclose(gh);
       }
 }
      printf("total=%d\n",total);
     return 0;
}

`

Yes, you can open multiple files using single file pointer, but before opening one file close the file using fclose() which was previously opened.

So in the loop first open the file and after doing operations close it before the loop ends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM