用D的方式写这个是什么? [英] What is the D way to write this?

查看:49
本文介绍了用D的方式写这个是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用C语言编写了该程序,还用为了练习,我尝试用D重写.一个朋友也用D编写了它,但是

To practice I tried to rewrite in D. A friend also wrote it in D but wrote it differently

步骤很简单.伪代码:

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

我的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);
  }   
}

似乎我不能只在arr上使用fread.sizeof是16,当我到达减法部分时,它给出了分割错误.我无法自动分配静态数组,或者至少我不知道如何分配.我似乎也不能使用malloc,因为当我遍历字节时尝试投射void *时,它将给我错误.你会怎么写,或者我能做得更好?

It seems I can't just use fread on arr. sizeof is 16 and it gives segmentation fault when I get to the subtracting part. I can't auto alloc a static array, or at least I don't know how. I also can't seem to use malloc because it gives me errors when I try to cast the void* when I loop through the bytes. How would you write this, or, what could I do better?

推荐答案

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

again why do you expect to be able to read in the entire chunk into a single array (which size in bytes fits in a 64 bit long (possibly more that several petabytes) I made that comment in the other question as well

使用循环复制内容

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;
}

我正在使用 rawRead rawWrite 进行阅读并写

I'm using rawRead and rawWrite to read and write

这篇关于用D的方式写这个是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆