Search code examples
aixreaddir

Need to list all files in a directory on AIX


Have a program that needs to list all the files in a directory on AIX.

Have successfully done this on Windows:-

hFind = FindFirstFile(szDir, &ffd);

 if (hFind == INVALID_HANDLE_VALUE)
 {
   fprintf(stderr,"Can not scan for files.\n");
   goto MOD_EXIT;   
 }

 do
 {
   if (! (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
   {
     printf("File:%s\n",ffd.cFileName);
   }
 }
 while (FindNextFile(hFind, &ffd) != 0);

and on Linux:-

d = opendir(szDir);
if (!d)
{
  fprintf(stderr,"Can not open directory '%s'.\n",szDir);
  goto MOD_EXIT;    
}

while(dir = readdir(d))
{
  if (dir->d_type != DT_DIR)
  {
    printf("File:%s\n",dir->d_name);
  }
}
closedir(d);

readdir appears to exist on AIX, but from the manual it would appear it only returns directories not files. The field d_type does not exist in the dirent structure.


Solution

  • When readdir() refers to directory entries it means entries in the directory, not subdirectories of the directory. So you can get all the names from there.

    To discover if they are files or directories, the portable / reliable way is to to stat() the result. There are standard macros to test the st_mode returned in the stat buffer (e.g. S_ISDIR)