NULL when using fopen with xcode

跟風遠走 提交于 2019-12-12 23:11:20

问题


I am trying to initialize a multidimensional array from a file using C for a iPhone 4inch app but I can't open up the file using fopen. Whenever I try this I get a NULL:

FILE  *f;
f=fopen("/level1.rez", "r");

if (f == NULL)
{
    printf("Error Reading File\n");
    //exit (0);
}

I am not sure how to open files using C.

I tried this already:

I printed out the current working directory using getcwd but all I got was "/" and when I attached that to the file name I still got NULL.

I read that if you go to product > scheme > edit scheme then options you can change the current working directory but I don't see that option.

Also I read that you can use absolute paths like: /users/name/desktop/program but I am new to iOS development so I don't know if that is a good idea.

So how do I get fopen to work?


回答1:


You CAN specify absolute paths in iOS, but the path in your example is probably used in Mac OS, which is laid out a little differently. You can specify paths to fopen() as you say, but there is more work to finding out what the first part of that path really is.

The iOS puts all AppStore apps into folders with randomly generated sandbox directory names. It is basically the the hexadecimal string of a GUID. So you need to use methods from iOS frameworks to get the first part of the path (or URL) to your file.

If the file is part of the app bundle so it can ship with the app, then you will need to use NSBundle methods to find the path to the file.

If the file is generated or downloaded after the app starts up on the device, then you need to use NSFileManager methods to determine the path to the directory of the file. (Typically the Documents directory. You can build a directory structure of your choice within the sandbox.)



来源:https://stackoverflow.com/questions/23278735/null-when-using-fopen-with-xcode

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