[mercury-users] io.m, directory listing

Tomas By tomas at research.nj.nec.com
Wed Oct 6 13:10:01 AEST 1999


Hi all,

I'm trying to add a `dir' function to io.m but I'm getting strange
results (ie lots of empty strings among the correct file names, file
names containing non-printable codes, file names that doesn't actually
exist but look like truncated versions of existing ones).

Can anyone see anything obvious? I'm using Linux if that matters.

/Tomas

--- add to io.m ------------------------------------------------------
:- interface.

% io__dir( Name, Files, IO_state, IO_state )
%   Returns a list of all files in the directory `Name'.

:- pred io__dir(string,io__res(list(string)),io__state,io__state).
:- mode io__dir(in,out,di,uo) is det.

:- implementation.

%:- pred io__dir(string,io__res(list(string)),io__state,io__state).
%:- mode io__dir(in,out,di,uo) is det.

:- pragma c_header_code("#include <stddef.h>").
:- pragma c_header_code("#include <stdio.h>").
:- pragma c_header_code("#include <sys/types.h>").
:- pragma c_header_code("#include <dirent.h>").
:- pragma c_header_code("#include <errno.h>").

io__dir(Name,Result,IO0,IO) :-
  io__c_dir(Name,RevFiles,Code,IO0,IO1),
  ( Code = -1 ->
    io__make_err_msg("can't open directory: ",Msg,IO1,IO),
    Result = error(Msg)
  ; list__reverse(RevFiles,Files),
    Result = ok(Files),
    IO = IO1 ).

:- pred io__c_dir(string,list(string),int,io__state,io__state).
:- mode io__c_dir(in,out,out,di,uo) is det.

:- pragma c_code(io__c_dir(Name::in,Files::out,Cde::out,IO0::di,IO::uo),
  [may_call_mercury],
 "DIR* dp;
  struct dirent* ep;

  Files = c_my_list_empty();

  dp = opendir(Name);

  if (dp == NULL)
  {
    Cde = -1;
  }
  else
  {
    while (ep = readdir(dp),ep)
    {
      Files = c_my_list_cons((String)ep->d_name,Files);
    }

    (void)closedir(dp);

    Cde = 0;
  }

  update_io(IO,IO0);").

:- pragma export(my_list_empty = out,"c_my_list_empty").
:- func my_list_empty = list(string).
:- mode my_list_empty = out is det.

my_list_empty = [].

:- pragma export(my_list_cons(in,in) = out,"c_my_list_cons").
:- func my_list_cons(string,list(string)) = list(string).
:- mode my_list_cons(in,in) = out is det.

my_list_cons(X,Xs) = [X|Xs].
----------------------------------------------------------------------
--------------------------------------------------------------------------
mercury-users mailing list
post:  mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-users-request at cs.mu.oz.au Message: subscribe
--------------------------------------------------------------------------



More information about the users mailing list