D 的写法是什么?
为了练习,我尝试用 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
我的 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* 时,它会给我错误。你会怎么写这个,或者我可以做得更好吗?
I wrote this program in C and also in erlang
To practice I tried to rewrite in D. A friend also wrote it in D but wrote it differently
The steps are simple. Pseudocode:
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
My D attempt:
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);
}
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
再说一次,为什么你期望能够将整个块读入单个数组(其大小以字节为单位适合 64 位长(可能超过几个拍字节)我也在另一个问题中发表了评论
使用复制内容的循环
我正在使用
rawRead
和rawWrite
读取和写入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
use a loop to copy the contents
I'm using
rawRead
andrawWrite
to read and writearr
不是指针,并且不会像 C 和 C++ 中那样转换为指针。如果您想要一个指向数组开头的指针,请使用 arr.ptr。
要分配静态数组,您可以使用:
但是,
N
必须是编译时常量(就像在 C 和 C++ 中一样),因此它在这里可能没有多大用处。arr
is not a pointer, and does not convert to a pointer like it does in C and C++.If you want a pointer to the start of the array, use
arr.ptr
.To allocate a static array, you use:
However,
N
must be a compile time constant (just like in C and C++), so it may not be much use here.