2012-01-02 60 views
5

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

看來我不能只用FREAD上ARR。 sizeof是16,當我到達減法部分時它給出了分段錯誤。我不能自動分配一個靜態數組,或者至少我不知道如何。我也似乎無法使用malloc,因爲當我嘗試在通過字節循環時拋出void *時,它會給出錯誤。你會如何寫這個,或者,我能做得更好?

+2

確定'&arr'指向數組的第一個元素? – hvd 2012-01-02 23:52:41

回答

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

我使用rawReadrawWrite讀寫

3

arr不是一個指針,並且不會像在C和C++中那樣轉換爲指針。

如果您想要一個指向數組開頭的指針,請使用arr.ptr

要分配一個靜態數組,可以使用:

ubyte[N] arr; 

然而,N必須是一個編譯時間常數(就像C和C++),所以它可能沒有多大用處在這裏。

相關問題