utils.c 1.78 KB
Newer Older
1
/****************************************************************************
2
 * Utility functions                                                       *
3 4 5
 ****************************************************************************/

/**
6
 * @file utils.c
7
 * @author Celine Mercier (celine.mercier@metabarcoding.org)
8 9
 * @date 29 March 2016
 * @brief Code for utility functions.
10 11
 */

12 13 14 15 16
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
17 18
#include <stdlib.h>
#include <dirent.h>
Celine Mercier committed
19
#include <unistd.h>
20
#include <time.h>
21

22
#include "utils.h"
23 24 25 26
#include "obidebug.h"
#include "obierrno.h"


27
#define DEBUG_LEVEL 0	// TODO has to be defined somewhere else (cython compil flag?)
28 29


30 31 32 33 34 35 36

/**********************************************************************
 *
 * D E F I N I T I O N   O F   T H E   P U B L I C   F U N C T I O N S
 *
 **********************************************************************/

37

38
int count_dir(char* dir_path)
39
{
40 41 42
	struct dirent* dp;
	DIR*           fd;
	int            count;
43 44

	count = 0;
45
	if ((fd = opendir(dir_path)) == NULL)
46 47
	{
		obi_set_errno(OBI_UTILS_ERROR);
48
		obidebug(1, "Error opening a directory: %s\n", dir_path);
49 50 51 52 53 54 55 56
		return -1;
	}
	while ((dp = readdir(fd)) != NULL)
	{
		if ((dp->d_name)[0] == '.')
			continue;
		count++;
	}
57

58 59
	return count;
}
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86


char* obi_format_date(time_t date)
{
	char*       formatted_time;
	struct tm*  tmp;

	formatted_time = (char*) malloc(FORMATTED_TIME_LENGTH*sizeof(char));

	tmp = localtime(&date);
	if (tmp == NULL)
	{
		obi_set_errno(OBICOL_UNKNOWN_ERROR);
		obidebug(1, "\nError formatting a date");
		return NULL;
	}

	if (strftime(formatted_time, FORMATTED_TIME_LENGTH, "%c", tmp) == 0)
	{
		obi_set_errno(OBICOL_UNKNOWN_ERROR);
		obidebug(1, "\nError formatting a date");
		return NULL;
	}

	return formatted_time;
}