繁体   English   中英

使用单个文件指针打开多个文件

[英]Open multiple files using single file pointer

我可以在一个循环中使用单个文件指针打开多个文件吗? 我有一个包含 50 个文件名的字符串数组。它只显示一个文件名,然后发生分段错误。 请建议。

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;
}

`

是的,您可以使用单个文件指针打开多个文件,但在打开一个文件之前,请使用之前打开的 fclose() 关闭文件。

所以在循环中首先打开文件,然后在循环结束之前关闭它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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