简体   繁体   English

在Cocoa中创建具有固定大小的文件

[英]Create file with fixed size in Cocoa

My MAC app need create file that has fixed size. 我的MAC应用程序需要创建具有固定大小的文件。 Example : I want to create file has name : test.txt, fixed size : 1069 bytes. 示例:我要创建的文件名为:test.txt,固定大小:1069字节。 How can i do that? 我怎样才能做到这一点? I use below code to write file : 我用下面的代码写文件:

NSError *err;
NSString* arrayText = [writeArray componentsJoinedByString: @"\n"];

[filemgr createFileAtPath:[NSString stringWithFormat:@"%@/test.txt",sd_url] contents:nil attributes:nil];
[arrayText writeToFile:[NSString stringWithFormat:@"%@/test.txt",sd_url] atomically:YES encoding:NSUTF8StringEncoding error:&err];

Thanks 谢谢

This function will write some junk data to file. 此功能将一些垃圾数据写入文件。

+(BOOL)writeToFile:(NSString *)path  withSize:(size_t)bytes;
{
    FILE *file = fopen([path UTF8String], "wb"); 
    if(file == NULL)
        return NO;

    void *data = malloc(bytes);  // check for NULL!
    if (data==NULL) {
        return NO;
    }
    fwrite(data, 1, bytes, file);
    fclose(file);
    return YES;
}

If you dont want to use fwrite 如果您不想使用fwrite

+(BOOL)writeToFile:(NSString *)path  withSize:(size_t)bytes;
{
    void *data = malloc(bytes);  // check for NULL!
    if (data==NULL) {
        return NO;
    }
    NSData *ldata   = [NSData dataWithBytes:data length:bytes];
    [ldata writeToFile:path atomically:NO];
    return YES;
}

In order for the file to contain a certain number of bytes, you must write that many bytes to the file. 为了使文件包含一定数量的字节,必须将那么多字节写入文件。 There's no way to make a file's size be something other than the number of bytes it contains. 除了文件包含的字节数之外,没有办法使文件的大小有所变化。

You can use FSAllocateFork (or fcntl with F_PREALLOCATE ) to reserve space to write into. 可以使用FSAllocateFork (或fcntlF_PREALLOCATE )来保留要写入的空间。 You'd use this, for example, if you were implementing your own download logic (if, for some reason, NSURLDownload wasn't good enough) and wanted to (a) make sure enough space is available for the file you're downloading and (b) grab it before something else does. 例如,如果您要实现自己的下载逻辑(如果由于某种原因,NSURLDownload不够好),并且想要(a)确保要下载的文件有足够的空间,则可以使用此方法(b)先抢夺它。

But, even that doesn't actually change the size of the file, just ensures (if successful) that your writes will not fail for insufficient space. 但是,即使那实际上并没有改变文件的大小,也只要确保(如果成功)写操作不会因空间不足而失败。

The only way to truly grow a file is to write to it. 真正增长文件的唯一方法是写入文件。

The best way to do that is to use either -[NSData writeToURL:options:error:] , which is the easy way if you have the data all ready at once, or NSFileHandle, which will enable you to write the data in chunks rather than having to build it all up in memory first. 最好的方法是使用-[NSData writeToURL:options:error:] (这是您一次准备好所有数据的简便方法),或者使用NSFileHandle,这将使您可以分块地写入数据而不是必须先将其全部构建在内存中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM