【问题标题】:What is the D way to write this?写这个的D方式是什么?
【发布时间】:2012-01-03 08:54:19
【问题描述】:

I wrote this program in Cin erlang

为了练习,我尝试用 D 重写。一个朋友也用 D 写过,但是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* 时,它会给我带来错误。你会怎么写这个,或者,我能做些什么更好?

【问题讨论】:

  • 你确定&amp;arr指向数组的第一个元素吗?

标签: d


【解决方案1】:

再次,为什么您希望能够将整个块读入单个数组(以字节为单位的大小适合 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;
}

我正在使用rawReadrawWrite 进行读写

【讨论】:

    【解决方案2】:

    arr 不是指针,不会像在 C 和 C++ 中那样转换为指针。

    如果您想要指向数组开头的指针,请使用arr.ptr

    要分配静态数组,请使用:

    ubyte[N] arr;
    

    但是,N 必须是编译时常量(就像在 C 和 C++ 中一样),所以这里可能用处不大。

    【讨论】:

      猜你喜欢
      • 2011-03-07
      • 1970-01-01
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多