/** @file
 * $Source: /home/cvsmanager/yoda/event/DirectoryStructure.c,v $
 * $Id: DirectoryStructure.c,v 5.1 2006/02/04 12:37:43 kusanagi Exp $
 * $Author: kusanagi $
 * 
 * Implementation of the CreateDirectoryStructure function.
 */

#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include "DirectoryStructure.h"

/**
 * Create all directories that are needed to create a certain file name.
 * @param FileName file name with the path.
 * @retval 0 everything was OK.
 * @retval -1 an error occurred, errno is set accordingly.
 */
int CreateDirectoryStructure(const char *FileName) {
  const char *pathend;
  char *path = malloc(strlen(FileName) + 1);
  struct stat buf;

  for (pathend = FileName+1; pathend != NULL; 
       pathend = strchr(pathend+1, '/')) {
    strncpy(path, FileName, (pathend - FileName));
    path[pathend - FileName] = '\0';
    if (stat(path, &buf) != 0) {
      if (mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) != 0) {
	return -1;
      }
    }
  }
  return 0;
}

