我可以在一个循环中使用单个文件指针打开多个文件吗?我有一个包含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;
}
`
显示你所尝试过的东西,即使你认为它是错误的。 –
您可以使用文件指针打开单个文件。您可以重新使用文件指针来打开另一个文件,但在关闭之前打开的文件之后。所以步骤如下 1.使用文件指针打开文件 2.使用文件指针关闭文件 3.再次重新使用文件指针打开另一个文件。 –
@ rabi shaw我已经完成了它,但它给出了分段错误。 –