Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fopen() in Objective-C

I am puzzled by a crash I keep getting due to an error at this section of code:

                FILE *fid200;
                fid200 = fopen ( "Length200Vector.txt" , "w" );
                if (fid200 == NULL)
                    perror("Error opening Length200Vector.txt");
                for (int n = 0; n<200; n++) {
                    if (n == 0) {
                        fprintf (fid200, "%f", self.avgFeatureVect[0][n]);
                    }
                    else {
                    fprintf (fid200, ", %f", self.avgFeatureVect[0][n]);
                    }
                }
                fprintf (fid200, "\n");
                fclose(fid200);

The error is: Error opening Length200Vector.txt: Operation not permitted.

The file is residing in my Resources folder for my project and this line is being executed in a .mm file. Within the same project in .cpp files I am using practically the same exact code which runs without a problem. Can't seem to figure this one out...

Thanks

like image 958
Kevin_TA Avatar asked Nov 17 '11 23:11

Kevin_TA


1 Answers

Regarding your comment that this is an iOS App: you are not allowed (in terms of the iOS sandbox) to perform modifying ("w" in fopen()) file access to anything in iOS applications other than to files located in your applications "Documents" directory (or for general application resources the ~/Library/Application Support/"bundle ID" directory and for temporary files the directory that is returned by a call to the NSTemporaryDirectory() function[1]).

Get access to the "Documents" directory by something like this

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docs_dir = [paths objectAtIndex:0];

If you have a resource file already that you will need to modify during the execution of your app, you will have to copy it to the "Documents" directory first, then modify it.

[1] http://developer.apple.com/library/ios/#documentation/FileManagement/Conceptual/FileSystemProgrammingGUide/AccessingFilesandDirectories/AccessingFilesandDirectories.html#//apple_ref/doc/uid/TP40010672-CH3-SW1

like image 152
cli_hlt Avatar answered Nov 15 '22 20:11

cli_hlt