Home > Mobile >  Xcode can't find files that exist (using c fopen)
Xcode can't find files that exist (using c fopen)

Time:09-18

I've been running into this strange problem lately where in my Cocoa app project in Xcode I get the error that the file was not found when using "fopen" (errno 2), called from a C file. I made sure to copy these files into the project's directory, then I dragged them from the Finder directory into the Xcode project tree. And finally, in the scheme's options I checked "use custom directory" and entered the directory where I have the project and all the files. The programme builds fine, but during runtime I get a BAD ACCESS error and I can see that my FILE* variable is still NULL. The command that throws the exception is actually "fread" two lines later, but it's only because "fopen" didn't do its job.

This whole setup has worked fine before in pure C projects. But this is different because it started as a Cocoa app in Objective-C (because I intended to use C for the programme's main logic). At some point I also had to change the extensions of all the ".m" files to ".mm" or the compiler wouldn't even find the C standard library! (but this is probably beside the point)

So the question is.. what else do I need to check in order to have the programme find the files I'm trying to open?

NOTE: the backbone of the project is written in C , and I'm only using Cocoa in order to be able to dram images on the screen, so if anyone has a better approach to including graphics in a C project I'm all ears.

Thanks for reading

EDIT: I'm using Xcode 12.4 and Catalina 10.15.7

CodePudding user response:

Cocoa apps do not work with files the same way as command-line C apps. Cocoa apps create an app bundle, which is where the files you want to read should be. If you have files you want to read in a Cocoa app, add them to the project. When you add the files to the project, they will get copied to the app bundle. Make sure they are in the app target's Copy Bundle Resources build phase.

enter image description here

Use the methods in the Bundle class to locate the files instead of fopen. The following Swift code locates a file named "MyFile.txt" in the main app bundle:

let mainBundle = Bundle.main
let fileURL = mainBundle.url(forResource: "MyFile", withExtension: "txt")
  • Related