Reading a file eats whole memory

Jarrett Billingsley kb3ctd2 at yahoo.com
Sun Oct 21 08:39:11 PDT 2007


"div0" <div0 at users.sourceforge.net> wrote in message 
news:fffqid$1csk$1 at digitalmars.com...
>
> You are trying to read a string in, so I guess the routine is using the 
> 1st four bytes as a string length count. That's how tango works anyway 
> IIRC.
>
> -- 

You are precisely right.

If you just want to get all the data in a file, just do:

import std.file;

int main(char[][] args)
{
    ubyte[] data = cast(ubyte[])std.file.read(args[0]);
    return 0;
}

Two things: one, std.file.read returns a void[], which is a bit like D's 
equivalent of a void* -- it can point to anything, but you can't modify its 
data, and it also has a length which indicates the number of bytes in the 
data.  Two, I'm casting to ubyte[] instead of char[].  Do NOT use char[] for 
"plain old data" as in C.  char is a UTF-8 datatype, not a "one byte" 
datatype.  You'll most likely get errors unless your input file is all plain 
ASCII or UTF-8 text.  D provides the byte and ubyte types for raw byte data. 




More information about the Digitalmars-d-learn mailing list