파일명으로 sort하는 방법.

xog2000의 이미지

ls -al을 실행하면

파일명과 디렉토리 명이 정렬 되어서 나타납니다.

이를 구현 하고자 한다면

디렉토리의 내용을 읽어 드린 후

그것을 토대로 정렬하는 방법 밖에 없습니까?

그렇다면 파일명으로 정렬 시 어떤 정렬 방법을 사용해야 하는지

도움을 부탁드립니다.

ps. 제가 만든 프로그램 중 하나는 이 문제로 인해
fifo나 파일을 생성하여 ls -al명령 재지향 해서 사용한 적이 있습니다.
이런 방식을 피하고 싶습니다.

mach의 이미지

질문이 C언어를 사용하겠다는 것인지 모르지만 답변드립니다.

리눅스등에서 쓰겠다면, scandir()을 이용하시면 좋다기 보다는 하여간, 편리합니다.

Solaris/SunOS에서 사용하려면, 아래 소스처럼, opendir() readdir등과 소팅 알고리즘을 동원하여 만들어야 합니다.
(참고소스)

#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
 
 
int scandir(const char *dir, struct dirent ***namelist,
            int (*select)(const struct dirent *),
            int (*compar)(const struct dirent **, const struct dirent **))
{
  DIR *d;
  struct dirent *entry;
  register int i=0;
  size_t entrysize;
 
  if ((d=opendir(dir)) == NULL)
     return(-1);
 
  *namelist=NULL;
  while ((entry=readdir(d)) != NULL)
  {
    if (select == NULL || (select != NULL && (*select)(entry)))
    {
      *namelist=(struct dirent **)realloc((void *)(*namelist),
                 (size_t)((i+1)*sizeof(struct dirent *)));
	if (*namelist == NULL) return(-1);
	entrysize=sizeof(struct dirent)-sizeof(entry->d_name)+strlen(entry->d_name)+1;
	(*namelist)[i]=(struct dirent *)malloc(entrysize);
	if ((*namelist)[i] == NULL) return(-1);
	memcpy((*namelist)[i], entry, entrysize);
	i++;
    }
  }
  if (closedir(d)) return(-1);
  if (i == 0) return(-1);
  if (compar != NULL)
    qsort((void *)(*namelist), (size_t)i, sizeof(struct dirent *), compar);
 
  return(i);
}
 
int alphasort(const struct dirent **a, const struct dirent **b)
{
  return(strcmp((*a)->d_name, (*b)->d_name));
}

------------------ P.S. --------------
지식은 오픈해서 검증받아야 산지식이된다고 동네 아저씨가 그러더라.

------------------ P.S. --------------
지식은 오픈해서 검증받아야 산지식이된다고 동네 아저씨가 그러더라.