[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: New version of function mkdirhier()



Svante Signell, le Thu 12 Jan 2012 18:07:46 +0100, a écrit :
> int
> mkdirhier(char *path)
> {
>   char *src, *dst = "";
>   char *dirp;
>   int retval = 1, len = 0;
> 
>   src = path;
>   if ((dst = calloc (0, strlen (src))) == NULL)

This will alloc 0*strlen(src) bytes. Probably not what you want. Why
using calloc() actually? malloc should be just fine, setting dst[0] = 0;
just after that. You also need to use strlen(src)+1, else you don't have
room for the 0-termination.

>     {
>       errno = ENOMEM;
>       return -1;
>     }
> 
>   /* Absolute path: Leading '/' */
>   if (path[0] == '/')
>     {
>     strncpy(dst, "/", 1);
>     src++;
>     }
> 
>   while ((dirp = strchr(src, '/')) != NULL)
>     {
>       len = dirp - src;
>       if (len == 0)
> 	{
> 	  src++;
> 	  continue;
> 	}
>       if (len == 1 && src[0] == '.')
> 	{
> 	  src++;
> 	  continue;
> 	}
>       if (len == 2 && src[0] == '.' && src[1] == '.')
> 	{
> 	  strncat(dst, src, len);
> 	  src = dirp + 1;
> 	  strncat(dst, "/", 1);
> 	  continue;
> 	} 
>       if (len > 0)
You don't need this test: you have already tested the 0 case above.

> 	{
> 	  strncat(dst, src, len);
> 	  src = dirp + 1;
> 	  if (mkdir(dst, 0777) == -1)
> 	    {
> 	      if (errno != EEXIST)
> 		{
> 		  free(dst);
> 		  return -1;
> 		}
> 	    }
> 	  else
> 	    retval = 0;
> 	  strncat(dst, "/", 1);
> 	}
>     }
> 
>   /* Create dir after last '/' or no '/' in path */
>   if ((dirp = strchr(src, '\0')) != NULL)

Why using strchr to look for \0? Simply use strlen to get the length
until the string termination.

Samuel


Reply to: