保存空白文件在Objective-C [英] Save blank file in Objective-C

查看:131
本文介绍了保存空白文件在Objective-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个code,除其他事项外,必须保存一零填充文件。它可以期望创建一个10MB的文件,甚至1GB的空白。

I am working on a code that, among other things, must save a zero-filled file. It can expect to create a file from 10MB to even 1GB blank.

它必须与此类似Unix命令:

It must be similar to this Unix command:

dd if=/dev/zero of=my_image.dsk count=20480

我可以做这个工作,小尺寸的:

I could do this one work with small sizes:

int totalSize = 1024*1024;
char buf[totalSize];
strcpy(buf,"");

NSData *theData = [NSData dataWithBytes:buf length:sizeof(buf)];

//NSLog(@"%@", theData);
NSLog(@"%lu", sizeof(buf));

[theData writeToFile:@"/Users/foo/Desktop/my_image.dsk" atomically:YES];

但是,如果我尝试一个更大的值(1024 * 1024 * 10,例如),它崩溃。
所以我尝试:

But if I try a bigger value (1024*1024*10, for instance), it crashes. So I tried:

NSFileManager *ddd = [[NSFileManager alloc ] init];
[ddd createFileAtPath:@"/Users/foo/Desktop/my_image.dsk" contents:[NSData data] attributes:nil];

它创建了一个空文件,但由于文件大小为零不好。它不应该是零。

It creates an empty file, but is not good because the file size is zero. It should not be zero.

我花了几个小时试图找到没有成功的答案。我想这样做在的OBJ-C,但C也是一种选择之前,我去坚果。

I spent hours trying to find an answer without success. I want to do this in Obj-C, but C is also an option before I go nuts.

请,有人给-我一些光芒!

Please, someone give-me some light!

在此先感谢!

- 编辑 -

谢谢大家,但一件事:有可能不会对内存分配的一切写

Thanks everyone, but one more thing: is it possible to write without allocating everything on memory?

推荐答案

您可以使用 DD 。这将让你写,例如,10 GB无需担心内存或地址空间。

You can use dd. This will let you write, e.g., 10 GB without worrying about memory or address space.

NSTask *task = [NSTask new];
long size = ...; // Note! dd multiplies this by 512 by default
NSString *path = ...;
[task setLaunchPath:@"/bin/dd"];
[task setArguments:[NSArray arrayWithObjects:@"dd", @"if=/dev/zero",
    [NSString stringWithFormat:@"of=%s", [path fileSystemRepresentation]],
    [NSString stringWithFormat:@"count=%ld", size],
    nil]];
[task launch];
[task waitUntilExit];
if ([task terminationStatus] != 0) {
    // an error occurred...
}
[task release];

一个优点是经验丰富的用户可以杀死 DD ,如果出现错误。

关于沙箱:我怀疑的是,这将正常工作,即使在沙箱中,但我很好奇,想知道。根据文件(<一个href=\"http://developer.apple.com/library/mac/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxDesignGuide.pdf\"相对=nofollow>链接),子进程继承简单地创建它的进程的沙盒。这就是你如何指望它在Unix上运行。

About sandboxing: My suspicion is that this will work fine even in a sandbox, but I'd be curious to know for sure. According to documentation (link), a subprocess "simply inherits the sandbox of the process that created it." This is exactly how you'd expect it to work on Unix.

您可以肯定的是 DD 将坚持围绕,因为苹果公司声称OS X符合SUSv3。

You can be sure that dd will stick around since Apple claims that OS X conforms to SUSv3.

这篇关于保存空白文件在Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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