Remove unwanted ' \r ' from an Array ... by reading a *.txt file.

Ali Çehreli acehreli at yahoo.com
Thu Oct 24 17:21:37 UTC 2019


On 10/24/2019 09:49 AM, Mil58 wrote:
> On Thursday, 24 October 2019 at 16:21:47 UTC, welkam wrote:
>> On Thursday, 24 October 2019 at 15:27:05 UTC, Mil58 wrote:
>>> [...]
>>
>> void main() {
>>     File("data.txt", "r+")
>>         .byLineCopy()
>>         .array()
>>         .each!writeln;
>> }
>>
>> byLineCopy removes the new lines. If in the future you would need the 
>> new line symbol call byLineCopy(Yes.keepTerminator)
> 
> Sorry but not working ... Surely i'm not able to insert and adapt to my 
> own script !  :-(
> Could you, please, modify with the right syntax at the right place ? - 
> Thanks.

The following program works for me.

As I'm on Linux, I had to write a makeFile() function to generate the 
file to ensure '\r' line endings. (Otherwise I would get '\n'.)

'result's type is string.

import std.stdio;
import std.file;
import std.algorithm : each, joiner, map;
import std.array : array, empty;
import std.conv : text;
import std.typecons : No;

void makeFile(string fileName) {
   const lines = ["abcd", "1234", "03b52h"];
   auto fishier = File(fileName, "w");
   lines.map!(l => l ~ '\r').each!(l => fishier.write(l));
}

void main() {
   enum fileName = "values_test.txt";

   makeFile(fileName);

   auto lines = File(fileName, "r").byLineCopy(No.keepTerminator, '\r');
   auto result = lines.joiner("-").text;
   writeln(result);
}

Ali



More information about the Digitalmars-d-learn mailing list