collinm wrote:
hi
i expect to find 7 file on a folder... maybe less, maybe more...
i can surely put this number to 1... but i think doing some realloc
will be expensive...
after 7 files, i need to use realoc...
somebody could help me to use realloc?
[code]
int searchfile(char *dir, char *filename, int flength, char *ext)
{
DIR *pdir;
printf("dir: %s\n",dir);
pdir = opendir(dir);
struct dirent *pent;
char **fileArray;
int lenFile=20;
int fileCount=0;
int expectedFile=7;
fileArray = (char**) malloc( expectedFile * sizeof(char*) );
if (!pdir)
{
printf ("fct: searchfile - %s - Incapable d'utiliser
opendir()\n", strerror (errno));
return 1;
}
............ code snipped *********
Ignoring the non-standard code, I see something that doesn't
look right. You have called function malloc to reserve memory
before you check pdir. This will lead to a memory leak should
pdir have value !pdir. Also, you fail to chech the return value
of malloc. The allocation could fail.
You are using dynamic allocations for a fixed size of 7 strings
of 20 chars. You might as well forego dynamic allocations, change
char **fileArray;
to char fileArray[7][20];
and you will have storage
If the insist on dynamic allocations, I would encapsulate
char **fileArray and int fileCount in a struct and write
functions that manipulates the struct.
Example,
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct STRINGARR
{
char **String;
size_t nelem;
} STRINGARR;
/* Prototypes */
char *AddSTRINGARR(S TRINGARR *p, const char *s);
void PrintSTRINGARR( STRINGARR *p, const char *s);
void FreeSTRINGARR(S TRINGARR *p);
int main(void)
{
STRINGARR fnames = {NULL}; /* Emply array of file names */
/*************** *************** *************** ***********
* TODO: add variables and code to search the directory *
* and for each match call function AddSTRINGARR *
* example: AddSTRINGARR(&f names, filename); *
*************** *************** *************** ***********/
/* Example */
AddSTRINGARR(&f names,"hello.c" );
AddSTRINGARR(&f names,"GoodMorn ing.c");
AddSTRINGARR(&f names,"GoodNigh e.c");
PrintSTRINGARR( &fnames,"File") ;
FreeSTRINGARR(& fnames);
return 0;
}
char *AddSTRINGARR(S TRINGARR *p, const char *s)
{
char **tmp;
if((tmp = realloc(p->String,(size of *tmp)*(p->nelem+1))) == NULL)
return NULL;
if((tmp[p->nelem] = malloc(strlen(s )+1)) == NULL) return NULL;
strcpy(tmp[p->nelem],s);
p->String = tmp;
return p->String[p->nelem++];
}
void PrintSTRINGARR( STRINGARR *p, const char *s)
{
size_t i;
for(i = 0; i < p->nelem; i++)
printf("%s %u. %s\n",s?s:"",i+ 1,p->String[i]);
return;
}
void FreeSTRINGARR(S TRINGARR *p)
{
size_t i;
for(i = 0; i < p->nelem; i++) free(p->String[i]);
free(p->String);
p->String = NULL;
p->nelem = 0;
return;
}
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.c om/abowers822/