2012-01-02 27 views
5

I wrote this program in C y también in erlang¿Cuál es la forma D de escribir esto?

Para practicar Traté de volver a escribir en D. Un amigo también escribió en D, pero wrote it differently

Los pasos son simples. Pseudocódigo:

While not end of file: 
    X = Read ulong from file and covert to little endian 
    Y = Read X bytes from file into ubyte array 
    subtract 1 from each byte in Y 
    save Y as an ogg file 

Mi intento D:

import std.file, std.stdio, std.bitmanip, std.conv, core.stdc.stdio : fread; 
void main(){ 
    auto file = File("./sounds.pk", "r+"); 
    auto fp = file.getFP(); 
    ulong x; 
    int i,cnt; 
    while(fread(&x, 8, 1, fp)){ 
    writeln("start"); 
    x=swapEndian(x); 
    writeln(x," ",cnt++,"\n"); 
    ubyte[] arr= new ubyte[x]; 
    fread(&arr, x, 1, fp); 
    for(i=0;i<x;i++) arr[i]-=1; 
    std.file.write("/home/fold/wak_oggs/"~to!string(cnt)~".ogg",arr); 
    } 
} 

Parece que no puedo usar fread en arr. sizeof es 16 y da una falla de segmentación cuando llego a la parte de resta. No puedo autoasignar una matriz estática, o al menos no sé cómo. Tampoco puedo usar malloc porque me da errores cuando intento lanzar el vacío * cuando recorro los bytes. ¿Cómo escribirías esto o qué podría hacer mejor?

+2

¿seguro '& arr' apunta al primer elemento de la matriz? – hvd

Respuesta

5

de nuevo, ¿por qué esperas poder leer todo el fragmento en una única matriz (cuyo tamaño en bytes cabe en 64 bits de largo (posiblemente más que varios petabytes) hice ese comentario en la otra pregunta también?

utilizar un bucle para copiar el contenido

writeln("start"); 
x=swapEndian(x); 
writeln(x," ",cnt++,"\n"); 
ubyte[1024*8] arr=void; //the buffer 
      //initialized with void to avoid auto init (or declare above the for) 
ubyte b; //temp buff 
File out = File("/home/fold/wak_oggs/"~to!string(cnt)~".ogg", "wb"); 

b=fp.rawRead(arr[0..x%$]);//make it so the buffer can be fully filled each loop 
foreach(ref e;b)e-=1;//the subtract 1 each byte loop 
out.rawWrite(b); 
x-=b.length; 
while(x>0 && (b=fp.rawRead(arr[])).length>0){//loop until x becomes 0 
    foreach(ref e;b)e-=1; 
    out.rawWrite(b); 
    x-=b.length; 
} 

estoy usando rawRead y rawWrite a leer y escribir

3

arr no es un puntero, y no se convierte en un puntero como lo hace en C y C++.

Si desea un puntero al inicio de la matriz, use arr.ptr.

asignar una matriz estática, se utiliza:

ubyte[N] arr; 

Sin embargo, N debe ser una constante en tiempo de compilación (al igual que en C y C++), por lo que no puede ser de mucha utilidad aquí.

Cuestiones relacionadas