2016-03-16 54 views
-4

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

` 
+2

显示你所尝试过的东西,即使你认为它是错误的。 –

+0

您可以使用文件指针打开单个文件。您可以重新使用文件指针来打开另一个文件,但在关闭之前打开的文件之后。所以步骤如下 1.使用文件指针打开文件 2.使用文件指针关闭文件 3.再次重新使用文件指针打开另一个文件。 –

+0

@ rabi shaw我已经完成了它,但它给出了分段错误。 –

回答

-1

是的,你可以,但打开一个文件,关闭文件使用FCLOSE()这是以前打开之前打开使用单个文件指针多个文件。

所以在循环中首先打开文件,并在循环结束之前执行操作后关闭它。

+1

@ Ash我试过了,但没有奏效。 –

+1

收集fopen和read函数的返回值, read()在代码中只有两个参数,但它应该有三个参数。 – Ash

+0

@ Ash但仍然出现分段错误而没有读取功能。每当fopen和fclose出现分段故障时,都会发生。 –