Reading bytes and converting to int

joao joao.rab at hotmail.com
Sat Aug 25 13:49:18 PDT 2012


On Saturday, 25 August 2012 at 20:31:22 UTC, Jonathan M Davis 
wrote:
> On Saturday, August 25, 2012 22:18:50 joao wrote:
>> It's not hard, sorry, it's because I'm a begginner.
>> So, all I wanted to do was to open a file and read the first 4
>> bytes and then return the int value. The last part I managed to
>> do.
>> But the first I'm trying.
>> 
>> In Python it is something like this:
>> f = open('filename')
>> s = f.read(4)
>> ...
>> In D I don't know yet. I'm trying to do:
>> File f = File('filename')
>> Then I want to read just 4 bytes. I still don't know what 
>> method
>> is :P
>
> I believe that this will work;
>
> import std.stdio;
>
> auto file = File("filename");
> auto buffer = ubyte[](4);
> buffer = file.rawRead(buffer);
>
> rawRead will read in the type given, and it will read up to the 
> number of
> elements given (less if the file is shorter). If the elements 
> are ubyte, then
> the length of the array before passing it in will be the number 
> of bytes to
> read, and the length of the result is the number of bytes read.
>
> - Jonathan M Davis

Ok, so I tried both ways and gave errors:
import std.stdio, std.cstream, std.system, std.bitmanip;

File f = File("filename");
auto buf = f.rawRead(new ubyte[4]);
auto i = peek!(uint, Endian.littleEndian)(buf);

std.stdio.File conflicts with std.stream.File

and

auto file = File("filename");
auto buffer = ubyte[](4);
buffer = file.rawRead(buffer);
auto i = peek!(uint, Endian.littleEndian)(buffer);

found '[' when expecting '.' following ubyte and ']' when 
expecting identifier following 'ubyte'


More information about the Digitalmars-d-learn mailing list