Question

My MAC app need create file that has fixed size. Example : I want to create file has name : test.txt, fixed size : 1069 bytes. 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

Was it helpful?

Solution

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

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

OTHER TIPS

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. 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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top