Wednesday, February 22, 2012

How to read a file in Xcode project

Recently I got stuck with an objective C problem, Given a text file in your Xcode project, how could I read this text file in my Xcode 4.2 project?
For example, you got a text file called test.txt, it has some contents. In your Xcode project, you need to read its file and print its content. It sounds easy at the beginning, but end up really tough, especially you are new with the latest version of Xcode.
The key problem is you need to make sure the file test.txt is put as the same folder as the build target file, which is the Products folder, otherwise you will always get the file not existed exception.

Through several times try out, finally I figure out how to do it.

1. Add your file into project
   Select File - Add File into xxx, chose the created file into project.
2. Add a "copy file" build phase
    View - Navigator - Show Project Navigator, chose Project, select targets, select Build phase,
    and click "Add Build Phase", add "Copy files";
    in the new Copy Files build phase, choose
      Destination - "Production Directory"
     and click "+" symbol, then choose the file test.txt in your project.

How to test if the file was added in the Product folder or not?
After press the "Run" button, you will see the executable target file under the "Product" folder of your Xcode project,select the target file, right click, select "Show in Finder", then the Product Folder will pop up in the Finder Application, then you should see the test.txt file in the same folder.


  1. Thank you very much!

  2. Thanks a lot! I was trying to figure out how to let my program know about my shaders at runtime.

  3. Thanks so much for the help, been all over the net looking and your the first to clearly point what to do. Lifesaver.

  4. iPhone APP Development Company is appreciating your efforts on article titled with How to read a file in Xcode project. Good job.