Reading unicode string with readf ("%s")

Ivan Kazmenko via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Nov 4 10:05:18 PST 2014


On Monday, 3 November 2014 at 20:03:03 UTC, Ali Çehreli wrote:
> On 11/03/2014 11:47 AM, Ivan Kazmenko wrote:
>> On Monday, 3 November 2014 at 19:37:20 UTC, Ivan Kazmenko 
>> wrote:
>>>    readf ("%s", &s);
>>
>> Worth noting: this reads to end-of-file (not end-of-line or 
>> whitespace),
>> and reading the whole file into a string was what I indeed 
>> expected it
>> to do.
>>
>> So, if there is an idiomatic way to read the whole file into a 
>> string
>> which is Unicode-compatible, it would be great to learn that, 
>> too.
>
> I don't know the answer to the Unicode issue with readf but you 
> can read the file by chunks:
>
> import std.stdio;
> import std.array;
> import std.exception;
>
> string readAll(File file)
> {
>     char[666] buffer;
>     char[] contents;
>     char[] piece;
>
>     do {
>         piece = file.rawRead(buffer);
>         contents ~= piece;
>
>     } while (!piece.empty);
>
>     return assumeUnique(contents);
> }
>
> void main () {
>     string s = stdin.readAll();
>
>     write (s);
> }
>
> Ali

Thank you for suggesting an alternative!
Looks like it would be an efficient one, too.
I believe it can be made a bit more efficient if using an 
appender, right?

Still, that's a lot of code for a minute scripting task, albeit 
one has to write the readAll function only once.


More information about the Digitalmars-d-learn mailing list