Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

iPhone - Size of file in app bundle

Hi,

Does anyone know if there is a way to get the size of a file in the application bundle? I have looked through the NSBundle and CFBundle documentation and I have not been able to find anything for this. I tried getting a URL to the file and the using NSFileHandle and the NSFileManager to get the file size, but I could not get that to work either.

Thanks,
Stephen

Mac Pro, Mac OS X (10.5.3), iPhone 2.0

Posted on Jul 18, 2008 12:02 PM

Reply
11 replies
Sort By: 

Jul 22, 2008 10:51 AM in response to rearcog

If you load it you can get the length, but I imagine you want to get the length before loading?

Here's how I load a file into memory and get the length:


NSString *filePath = [[NSBundle mainBundle] pathForResource:@"TWL06" ofType:@"txt"];
NSData *fileContents = [NSData dataWithContentsOfFile:filePath];
int len = fileContents.length;
char *p_data = new char[len+1];
[fileContents getBytes:p_data];
p_data[len]=0;


(I'm getting it into a null-terminated string, hence the +1 and the zero)
Reply

Jul 22, 2008 1:05 PM in response to orangekay

Here is what I tried


long getBundleFileLength(CFURLRef pdbUrl)
{
 CFStringRef path = CFURLCopyPath(pdbUrl);
 NSString* nsPath = (NSString*)path;
 
 NSFileManager* fileManager = [NSFileManager defaultManager];
 NSDictionary* attributes = [fileManager fileAttributesAtPath:nsPath 
 traverseLink:NO];
 //At this point attributes is nil
 NSNumber* fileSize = [attributes objectForKey:NSFileSize];
 
 CFRelease(path);
 return [fileSize intValue];
}


I know that the passed in CFURLRef is correct since I use the same URL with CFReadStreamCreateWithFile to create a valid CFReadStream. Maybe I am calling fileAttributesAtPath wrong since it returns nil. Looking at the path in the debugger it is

/Users/rearcog/Library/Application%20Support/iPhone%20Simulator/User/Application s/423647EC-B8A7-47F4-9AAB-AEBB3406F43F/BibleReader.app/myFile.pdb

This looks like the correct path to me.

Thanks,
Stephen
Reply

Jul 22, 2008 6:30 PM in response to rearcog

You can conserve stack space and reduce that all to about two lines, too:


long getBundleFileLength(CFURLRef pdbUrl)
{ 
 NSDictionary *attributes = [[NSFileManager defaultManager] fileAttributesAtPath: [(NSURL*)pdbUrl path] traverseLink: NO];
 
 return [[attributes objectForKey: NSFileSize] intValue];
}


Error checking would be a good idea, and something should also police the URL for validity; whether that belongs in this function or in the function that calls it is up to you.
Reply

iPhone - Size of file in app bundle

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.