473,778 Members | 1,910 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dynamic char - realloc use

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?

Expand|Select|Wrap|Line Numbers
  1. int searchfile(char *dir, char *filename, int flength, char *ext)
  2. {
  3. DIR *pdir;
  4. printf("dir: %s\n",dir);
  5. pdir = opendir(dir);
  6. struct dirent *pent;
  7. char **fileArray;
  8. int lenFile=20;
  9. int fileCount=0;
  10. int expectedFile=7;
  11. fileArray = (char**) malloc( expectedFile * sizeof(char*) );
  12.  
  13. if (!pdir)
  14. {
  15. printf ("fct: searchfile - %s - Incapable d'utiliser
  16. opendir()\n", strerror (errno));
  17. return 1;
  18. }
  19.  
  20. snprintf(tmp_mnt_dir_www, sizeof(tmp_mnt_dir_www),"%s/%s",
  21. mnt_dir_www, "ihist.htm");
  22. if((fp = fopen(tmp_mnt_dir_www, "w"))!=NULL)
  23. {
  24. while((pent = readdir(pdir)) != NULL)
  25. {
  26. if(strncmp(pent->d_name, filename, 5) == 0 &&
  27. strcmp(pent->d_name + flength, ext) == 0)
  28. {
  29. if(expectedFile<7)
  30. {
  31. fileArray[fileCount] = (char*) malloc( (lenFile+1)
  32. * sizeof(char) );
  33. }
  34. else
  35. fileArray = realloc( (char
  36. *)fileArray,(lenFile+1)*(sizeof (char);
  37.  
  38. fileCount++;
  39. strcpy( fileArray[fileCount], pent->d_name );
  40. }
  41. }
  42. ;
  43. fclose(fp);
  44. }
  45. for(i=0;i<fileCount;i++);
  46. free(fileArray[i]);
  47.  
  48. free( fileArray );
  49. closedir(pdir);
  50. return 0;
  51. }
  52.  
thanks

Nov 14 '05 #1
2 5351

# fileArray = (char**) malloc( expectedFile * sizeof(char*) );

# fileArray = realloc( (char
# *)fileArray,(le nFile+1)*(sizeo f (char);

Is that supposed to be sizeof(char*) instead sizeof(char)? That's a fourfold
difference on my machine.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
One of the drawbacks of being a martyr is that you have to die.
Nov 14 '05 #2


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/

Nov 14 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
29119
by: Robert | last post by:
Hi, How can i resize an array of strings to add more? This is an example i just downloaded from a website: char *cpArray; int i; for (i = 0; i < 10; i++) cpArray = (char *)malloc(20 * sizeof(char)); strcpy(cpArray, "A hat is on the mat");
8
3687
by: Peter B. Steiger | last post by:
The latest project in my ongoing quest to evolve my brain from Pascal to C is a simple word game that involves stringing together random lists of words. In the Pascal version the whole array was static; if the input file contained more than entries, tough. This time I want to do it right - use a dynamic array that increases in size with each word read from the file. A few test programs that make use of **List and realloc( List, blah...
6
2982
by: Materialised | last post by:
Hi Everyone, I apologise if this is covered in the FAQ, I did look, but nothing actually stood out to me as being relative to my subject. I want to create a 2 dimensional array, a 'array of strings'. I already know that no individual string will be longer than 50 characters. I just don't know before run time how many elements of the array will be needed. I have heard it is possible to dynamically allocate memory for a 2
3
2088
by: Thomas Christmann | last post by:
Hi! Sorry for the weird topic, I don't know how to describe it better... I have a little problem here I can't wrap my mind around. If I do: ------------------------------------- #define DWORD unsigned long #include <stdio.h> #include <malloc.h>
18
2446
by: intercom5 | last post by:
I'm writing a program in C, and thus have to use C strings. The problem that I am having is I don't know how to reallocate the space for a C string outside the scope of that string. For example: int main(void) { char *string1; string1 = malloc(6); sprintf(string1, "Hello");
8
2755
by: Steve Chow | last post by:
I have two structures; struct cordsys { int y, x, length }; struct provinces { int number; int type; struct cordsys cord;
13
2039
by: coosa | last post by:
Dear all, Using the conio implementation i wanted to create a dynamic string, whereby its size would be determined after each keyboard hit; in other words, i don't want to ask the user to specify the the size, but rather keep him/her typing and after each keyboard hit, the function getch() determines whether he/she entered the ENTER key to end the process; otherwise, increases the dynamic size or also decreases it if the back key was...
18
1615
by: hyperboogie | last post by:
Hello all I'm pretty new to C, so please accept my apologies in advance :-) I'm trying to allocate space for an array of pointers to strings (which are accepted as ellipses) inside a while loop, and after the allocation, when i "assert" the allocation, the assertion fails!!! void printStrings(s1, ...){ //ellipses function ....
4
1587
by: David d'Angers | last post by:
hi all i need a function that returns all the file names contained in a directory since the number of files is not known in advance how should i go about to use "dynamic array" to hold the file names ? can anyone post some code snippets please? thanks
0
9629
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9470
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10127
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10069
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9923
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8957
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5370
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5500
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3627
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.