gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:31:37 25 4
gpt4 key购买 nike

我可以在一个循环中使用单个文件指针打开多个文件吗?我有一个包含 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() 关闭文件。

因此,在循环中首先打开文件,然后在执行操作后在循环结束之前将其关闭。

关于c - 使用单个文件指针打开多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36029226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com