写这个的D方式是什么?

Jaz*_*Man 5 d

我用Cerlang 编写了这个程序

为了练习,我试图在D中重写.一位朋友也在D中了它,但是用不同的方式写了

步骤很简单.伪代码:

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
Run Code Online (Sandbox Code Playgroud)

我的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);
  }   
}
Run Code Online (Sandbox Code Playgroud)

看来我不能只是在arr上使用fread.sizeof是16,当我到达减法部分时它会给出分段错误.我无法自动分配静态数组,或者至少我不知道如何.我似乎也无法使用malloc,因为当我在循环遍历字节时尝试转换void*时,它会给我带来错误.你会怎么写这个,或者,我能做些什么呢?

rat*_*eak 5

再次为什么你希望能够将整个块读入一个单独的数组(大小以字节为单位,适合64位长(可能多于几PB))我在另一个问题中也做了这个评论

使用循环来复制内容

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;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用rawReadrawWrite阅读和写作