scandir 본문

Programming/C

scandir

halatha 2011. 5. 7. 05:08
출처: http://www.joinc.co.kr/modules/moniwiki/wiki.php/Code/C/Scandir
------------------ no sort
10BSize            
8192BValue         
8192BSize          
10A                
10BValue           
8192A              
1048576BValue      
1048576A           
524288BSize        
524288A            
524288BValue       
1048576BSize       

------------------ alphasort
1048576A           
1048576BSize       
1048576BValue      
10A                
10BSize            
10BValue           
524288A            
524288BSize        
524288BValue       
8192A              
8192BSize          
8192BValue         

------------------ versionsort
10A                
10BSize            
10BValue           
8192A              
8192BSize          
8192BValue         
524288A            
524288BSize        
524288BValue       
1048576A           
1048576BSize       
1048576BValue      

#include <stdio.h>
#include <unistd.h>	//	chdir
#include <dirent.h>
#include <string.h>
#include <stdlib.h>	//	exit
#include <sys/stat.h>	//	struct stat

void readDir(int nitems, struct dirent** items);

int main(int argc, char** argv)
{
	switch ( argc )
	{
		case 2: break;
		default:
			printf("Usage:\t%s [dir name]\n", argv[0]);
			exit(1);
			break;
	}

	int	i, nitems;
	char*	dir	=	argv[1];
	struct dirent**	items;

	if ( chdir(dir) < 0 )
	{
		printf("DIR: %s\n", dir);
		perror("chdir");
		exit(1);
	}

	printf("------------------ no sort\n");
	nitems	=	scandir(".", &items, NULL, 0);
	readDir(nitems, items);
	printf("\n------------------ alphasort\n");
	nitems	=	scandir(".", &items, NULL, alphasort);
	readDir(nitems, items);
	printf("\n------------------ versionsort\n");
	//	necessary to use -D_GNU_SOURCE when compile
	nitems	=	scandir(".", &items, NULL, versionsort);
	readDir(nitems, items);

	return	0;
}

void readDir(int nitems, struct dirent** items)
{
	int	i;
	for ( i = 0; i < nitems; ++i )
	{
		struct stat	fstat;

		if ( (!strcmp(items[i]->d_name, ".")) ||
			(!strcmp(items[i]->d_name, "..")) )
			continue;

		lstat(items[i]->d_name, &fstat);
		if ( (fstat.st_mode & S_IFDIR) == S_IFDIR )
		{
		}
		else
		{
			int	iLineNum	=	0;
			char	buf[256];
			FILE*	fp	=	fopen(items[i]->d_name, "r");
			if ( NULL == fp )
				continue;

			//	check how many numbers are in the file
			while ( fgets(buf, 255, fp) )	++iLineNum;

			rewind(fp);

			//	save each number in long pointer
			long*	plNums	=	(long*)malloc(sizeof(long) * iLineNum);
			iLineNum	=	0;
			while ( fgets(buf, 255, fp) )
			{
				*(plNums + iLineNum++)	=	atol(buf);
			}

			printf("%-20s\t%d lines\n", items[i]->d_name, iLineNum);

			//	clean up resources
			free(plNums);
			fclose(fp);
		}
	}
}
Comments