Mac OS X File Access

Started by
3 comments, last by Wudan 19 years, 1 month ago
Ok, I'm having what must be a really easy question to answer, but I can't find the answer to it anywhere. If I want to put files inside my Application Bundle (call it 'game.app'), how can I open the file in code? In Windows I use relative paths, and so far on Mac I've only been able to open files if I use the full path to the file I want to open. I'm using fopen(), reading the file, and ending with fclose(), really really basic stuff. From what I can tell from other Applications, they are reading files inside the bundle ... so why can't I? Thanks for any help you can offer in advance, I'm really stumped on this one :(
Advertisement
This page might be helpful:
Locating and Opening Bundles
Free Mac Mini (I know, I'm a tool)
Assuming you're programming in Obj-C, and the file you want to open is in the resources folder of your .app (ie, Whatever.app/Contents/Resources/Whatever.file), then this'll work:

FILE *file = fopen([[NSString stringWithFormat:@"%@/%s", [[NSBundle mainBundle] resourcePath], "Whatever.file"] cString], "rb");

[NSBundle mainBundle] returns the bundle of your .app, and resourcePath returns an NSString to the resources folder in your .app. Then just add a "/" and the file name and you can use fopen from there.

Read the NSBundle class docs and the link igni ferroque posted for more in depth info.

EDIT: Oops, typo in the code.
Thanks a ton guys :) I love gamedev.net :)

If I come up with a neat cross-platform way to read files I'll post some source code to do this. I'm sure I'm not the only neophyte to have this come up.
Ok, I've come up with some code to access files in the bundle, without knowing beforehand where the bundle is, and not using Objective C (as far as I know.)

This uses the Core Foundation framework.


#include <CoreFoundation/CFPreferences.h>char * sPath( char *name ){	char *path = 0;	CFBundleRef mainBundle;	CFURLRef execURL;	CFStringRef cfs_path;	int i, j;	CFIndex cfs_path_len;	i = 0;	j = 0;	int slashie = 0;		mainBundle = CFBundleGetMainBundle();	if( mainBundle ) execURL = CFBundleCopyExecutableURL( mainBundle );	if( execURL )	{		cfs_path = CFURLCopyFileSystemPath( execURL, 0 ); //2 is 'windows style ...'		cfs_path_len = CFStringGetLength( cfs_path );		path = new char [(int)(cfs_path_len)];		UniChar *buffer = new UniChar [(int)(cfs_path_len)];		CFStringGetCharacters( cfs_path, CFRangeMake(0, cfs_path_len), buffer);		//printf( "URL has %d chars\n", (int)(cfs_path_len) );		i = 0;		while( i < (int)(cfs_path_len) )		{			path = (char)(buffer);			if( path == '/' ) slashie = i;			if( i == (int)(cfs_path_len) ) break;			if( path == 0 ) break;			i++;		}		path = 0;		delete( buffer );	}	i = slashie+1;	j = 0;	while( 1 )	{		path = name[j];		if( name[j] == 0 ) break;		i++;		j++;	}	path = 0;	return path;}

This topic is closed to new replies.

Advertisement