Using fopen() in Objective-C

主宰稳场 提交于 2019-12-21 09:14:19

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/8176040/using-fopen-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!