How to resolve the algorithm Remove lines from a file step by step in the Erlang programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Remove lines from a file step by step in the Erlang programming language

Table of Contents

Problem Statement

Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2 Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Remove lines from a file step by step in the Erlang programming language

Source code in the erlang programming language

-module( remove_lines ).

-export( [from_file/3, task/0] ).

from_file( Name, Start, How_many ) ->
	{Name, {ok, Binary}} = {Name, file:read_file( Name )},
	Lines = compensate_for_last_newline( lists:reverse([X || X <- binary:split( Binary, <<"\n">>, [global] )]) ),
	{Message, Keep_lines} = keep_lines( Start - 1, How_many, Lines, erlang:length(Lines) - 1 ),
	ok = file:write_file( Name, [binary:list_to_bin([X, <<"\n">>]) || X <- Keep_lines] ), 
	io:fwrite( "~s~n", [Message] ).

task() ->
	file:copy( "priv/foobar.txt", "foobar.txt" ),
	from_file( "foobar.txt", 1, 2 ).



compensate_for_last_newline( [<<>> | T] ) -> lists:reverse( T );
compensate_for_last_newline( Reversed_lines ) -> lists:reverse( Reversed_lines ).

keep_lines( Start, _How_many, Lines, Available ) when Start > Available ->
	{"Start > avaliable. Nothing removed.", Lines};
keep_lines( Start, How_many, Lines, Available ) when Start + How_many  > Available ->
	Message = lists:flatten( io_lib:format("Start + How_many > avaliable. Only ~p removed.", [(Start + How_many) - Available]) ),
	{Keeps, _Removes} = lists:split( Start, Lines ),
	{Message, Keeps};
keep_lines( Start, How_many, Lines, _Available ) ->
	{Keeps, Removes} = lists:split( Start, Lines ),
	{"ok", Keeps ++ lists:nthtail( How_many, Removes )}.


  

You may also check:How to resolve the algorithm The sieve of Sundaram step by step in the Ruby programming language
You may also check:How to resolve the algorithm Count in factors step by step in the Fortran programming language
You may also check:How to resolve the algorithm Bitmap/Flood fill step by step in the D programming language
You may also check:How to resolve the algorithm Checkpoint synchronization step by step in the D programming language
You may also check:How to resolve the algorithm Gamma function step by step in the D programming language