All pastes #79483 Raw Edit

Anonymous

public text v1 · immutable
·published 2006-07-05 12:36 UTC
rendered paste body
char **get_files(char *tmp_path, int *num) {
	char	**buf;
	int		alloc_unit, i;
	struct	stat		statbuf;
	struct dirent	*dirp;
	DIR					*dp;
	
	alloc_unit = 0;
	i = 0;
	
	if( (buf = malloc(alloc_unit * sizeof(char *))) == NULL )
		err_exit("malloc error");
	alloc_unit = 2;
	
	if( (dp = opendir(tmp_path)) == NULL ) {
		err_exit("opendir error");
	}
	
	while ( (dirp = readdir(dp)) != NULL )	{
		
		if( stat(dirp->d_name, &statbuf) < 0)
			err_exit("stat error");
		
		if (strcmp(dirp->d_name, ".") == 0)
			continue;			/*	ignore current direcrory	*/
		else	{
			++i;
			if( i == (alloc_unit/2) ) {		/*	allocate more memory	*/
				if( (buf = realloc(buf, alloc_unit * sizeof(char *))) == NULL)
					err_exit("realloc error");
				alloc_unit += alloc_unit;
			}
			if( (buf[i-1] = malloc(2+ strlen(dirp->d_name))) == NULL)
				err_exit("malloc error");
			
			strcpy(buf[i-1], dirp->d_name);			/*	store the name of file/dir	*/

			if ( S_ISDIR(statbuf.st_mode) != 0 )	/*	it's a directory, add '/'	*/
				strcat(buf[i-1], "/");
		}
	}
	*num = i;
	return buf;
}