I wrote this program in C以及in erlang
为了练习,我尝试用D重写。一个 friend 也用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 *时,它将给我错误。您将如何编写此书,或者我能做得更好?
最佳答案
再次说明为什么您希望能够将整个块读入单个数组(以字节为单位的大小适合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;
}
我正在使用
rawRead
和 rawWrite
进行读写关于d - 用D的方式写这个是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8706466/