View of xos/tests/dirent.c


XOS | Parent Directory | View | Download

/* Copyright (C) 2008  Emmanuel Varoquaux
 
   This file is part of XOS.
 
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.
 
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
 
   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */
 
#include <error.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
 
int main()
{
  DIR *dirp;
  struct dirent *entry;
  long loc;
 
  if (!(dirp = opendir(".")))
    error(EXIT_FAILURE, errno, "opendir");
 
  errno = 0;
  if ((entry = readdir(dirp)))
    printf("%s\n", entry->d_name);
  else {
    if (errno)
      error(EXIT_FAILURE, errno, "readdir");
    puts("[End of directory.]");
  }
 
  errno = 0;
  if ((entry = readdir(dirp)))
    printf("%s\n", entry->d_name);
  else {
    if (errno)
      error(EXIT_FAILURE, errno, "readdir");
    puts("[End of directory.]");
  }
 
  loc = telldir(dirp);
 
  errno = 0;
  if ((entry = readdir(dirp)))
    printf("%s\n", entry->d_name);
  else {
    if (errno)
      error(EXIT_FAILURE, errno, "readdir");
    puts("[End of directory.]");
  }
 
  errno = 0;
  if ((entry = readdir(dirp)))
    printf("%s\n", entry->d_name);
  else {
    if (errno)
      error(EXIT_FAILURE, errno, "readdir");
    puts("[End of directory.]");
  }
 
  puts("[Seeking...]");
  seekdir(dirp, loc);
 
  errno = 0;
  if ((entry = readdir(dirp)))
    printf("%s\n", entry->d_name);
  else {
    if (errno)
      error(EXIT_FAILURE, errno, "readdir");
    puts("[End of directory.]");
  }
 
  puts("[Rewinding...]");
  rewinddir(dirp);
 
  while (1) {
    errno = 0;
    if ((entry = readdir(dirp)))
      printf("%s\n", entry->d_name);
    else {
      if (errno)
        error(EXIT_FAILURE, errno, "readdir");
      puts("[End of directory.]");
      break;
    }
  }
 
  if (closedir(dirp) == -1)
    error(EXIT_FAILURE, errno, "closedir");
 
  return EXIT_SUCCESS;
}