Iterate over each file in a directory

erlang is a strange language for me, this week I play in several languages ​​and I often come here for help, now I am on erlang and I'm stuck again :)

Basically, all I'm trying to do is the following, but in erlang:

Dim objFSO, objFile, objFolder

Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(currentDirectory))

For Each objFile in objFolder.Files
   do something with the file
   do something else
   do more stuff
Next

Nearest I came:

-export([main/1]).

main([]) -> 
find:files("c:\","*.txt", fun(F) -> {
       File, c:c(File)
}end).

clearly, it doesn’t work and nothing similar to how I need it ... but I tried many ways and read many examples, but just could not find a solution, maybe the language is simply not intended for this kind of thing?

And it is needed as escript (erlang script)

+5
source share
2 answers

It’s hard to recommend which method you should use because the pseudo-code “do something” is too vague.

- , Erlang: map fold.

: ? - (.. - ), (.. ) - , , (, )?

, , file:list_dir/1:

{ok, Filenames} = file:list_dir("some_directory"),

lists:foldl ( @legoscia, filelib:fold_files, , )

TotalSize = lists:foldl(fun(Filename,SizeAcc) ->
                FileInfo = file:read_file_info("some_directory/" ++ Filename),
                FileSize = FileInfo#file_info.size,
                SizeAcc + FileSize
            end, 0, Filenames).

Mapping

lists:map. = [{"somefile.txt",452}, {"anotherfile.exe",564},...]:

FileSizes = lists:map(fun(Filename) ->
                FileInfo = file:read_file_info("some_directory/" ++ Filename),
                FileSize = FileInfo#file_info.size,
                {Filename,FileSize}
            end,Filenames).

Foreach ( )

, - , lists:foreach, , , lists:map, ( ok):

, ".old" :

lists:foreach(fun(Filename) ->
                  OldFile = "some_directory/" ++ Filename,
                  NewFile = OldFile ++ ".old",
                  file:rename(OldFile, NewFile), 
              end,Filenames).

, - if map, fold, foreach ( , map filter) - - :

do_something_with_files([]) -> ok;
do_something_with_files([CurrentFile|RestOfFiles]) ->
   do_something(CurrentFile),
   do_something_with_files(RestOfFiles).

, Erlang, , VB, , , , , Erlang.

.. #file_info, file.hrl

-include_lib("kernel/include/file.hrl").
+11

, , , , , , . , , spawn . Functional Objects, , .

%% @doc This module provides the low level APIs for reading, writing,
%% searching, joining and moving within directories.
%% @end
-module(file_scavenger_utilities). %%% ------- EXPORTS ------------------------------------------------------------------------------- -compile(export_all). %%% ------- INCLUDES ----------------------------------------------------------------------------- %%% -------- MACROS ------------------------------------------------------------------------------ -define(IS_FOLDER(X),filelib:is_dir(X)). -define(IS_FILE(X),filelib:is_file(X)). -define(FAILED_TO_LIST_DIR(X), error_logger:error_report(["* File Scavenger Utilities Error * ", {error,"Failed to List Directory"},{directory,X}])). -define(NOT_DIR(X), error_logger:error_report(["* File Scavenger Utilities Error * ", {error,"Not a Directory"},{alleged,X}])). -define(NOT_FILE(X), error_logger:error_report(["* File Scavenger Utilities Error * ", {error,"Not a File"},{alleged,X}])). %%%--------- TYPES -------------------------------------------------------------------------------
%% @type dir() = string(). %% Must be containing forward slashes, not back slashes. Must not end with a slash %% after the exact directory.e.g this is wrong: "C:/Program Files/SomeDirectory/" %% but this is right: "C:/Program Files/SomeDirectory" %% @type file_path() = string(). %% Must be containing forward slashes, not back slashes. %% Should include the file extension as well e.g "C:/Program Files/SomeFile.pdf" %% -----------------------------------------------------------------------------------------------
%% @doc Enters a directory and executes the fun ForEachFileFound/2 for each file it finds %% If it finds a directory, it executes the fun %% ForEachDirFound/2. %% Both funs above take the parent Dir as the first Argument. Then, it will spawn an %% erlang process that will spread the found Directory too in the same way as the parent directory %% was spread. The process of spreading goes on and on until every File (wether its in a nested %% Directory) is registered by its full path. %% @end %% %% @spec new_user(dir(),funtion(),function())-> ok.

spread_directory (Dir, Top_Directory, ForEachFileFound, ForEachDirFound)            is_function (ForEachFileFound), is_function (ForEachDirFound) →   case? IS_FOLDER (Dir) of       false → ? NOT_DIR (Dir);       true →           F = fun (X) →                   FileOrDir = _: absname_join (Dir, X),                   case? IS_FOLDER (FileOrDir) of                       true →                           (catch ForEachDirFound (Top_Directory, FileOrDir)),                           spawn (fun() →                                   ? : spread_directory (FileOrDir, Top_Directory, ForEachFileFound, ForEachDirFound)                            );                       false →                           case? IS_FILE (FileOrDir) of                               false → {, not_a_file, FileOrDir};                               true → (catch ForEachFileFound (Top_Directory, FileOrDir))                                                             ,           case file: list_dir (Dir) of
{error, _} → ? FAILED_TO_LIST_DIR (Dir);               {ok, List} → : (F, List)              .

, :

E:\Applications>erl
Eshell V5.9  (abort with ^G)
1> Dir = "E:/Ruth".
"E:/Ruth"
2> TopDir = "E:/Ruth".
"E:/Ruth"
3> Folder = fun(Parent,F) -> io:format("\n\t~p contains Folder: ~p~n",[Parent,F]) end.
#Fun<erl_eval.12.111823515>
4> File = fun(Parent,F) -> io:format("\n\t~p contains File: ~p~n",[Parent,F]) end.
#Fun<erl_eval.12.111823515>
5> file_scavenger_utilities:spread_directory(Dir,TopDir,File,Folder).
    "E:/Ruth" contains File: "e:/Ruth/Thumbs.db"        

    "E:/Ruth" contains File: "e:/Ruth/Robert Passport.pdf"

    "E:/Ruth" contains File: "e:/Ruth/new mixtape.mp3"

    "E:/Ruth" contains File: "e:/Ruth/Manning - Java 3d Programming.pdf"

    "E:/Ruth" contains File: "e:/Ruth/jcrea350.zip"

    "E:/Ruth" contains Folder: "e:/Ruth/java-e books"

    "E:/Ruth" contains File: "e:/Ruth/Java Programming Unleashed.pdf"        

    "E:/Ruth" contains File: "e:/Ruth/Java Programming Language Basics.pdf"

    "E:/Ruth" contains File: "e:/Ruth/java-e books/vb blackbook.pdf.pdf"

+2

All Articles