New to Xcode can't open files in c++?

前端 未结 6 705
暖寄归人
暖寄归人 2020-11-30 19:26

I\'ve been using windows in a class I\'ve been taking but I am trying to run a basic code to figure out how to open/close/input/output from files on Xcode and the code I usu

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 20:13

    I've struggled with the same problem today. I wanted to add C code to my Swift project and my file pointer was always NULL.

    Unfortunately, in XCode 9 for iOS app, I couldn't change the working directory. Changing Build phases didn't help me either. After 4+ hours of trial and error, that's what I've come up with finally and it works:

    1. when copying files to XCode, I've chosen "Create groups", but I needed to choose "Create folder references":

    1. I created a new objective-c file (.m) and copied all my C code there.

    2. I left untouched .h files (XCode generated bridging header and my own .h file with public functions declaration). Now my project structure looked like this:

    1. In my dict.m file in place of previous plain c fopen part:

      FILE *dic = fopen("dictionary.txt", "r");
      

      I added obj-C code:

      NSString *filePath = [[NSBundle mainBundle] pathForResource:@"dictionary" ofType:@"txt"];
      FILE *dic = fopen([filePath cStringUsingEncoding: NSUTF8StringEncoding], "r");
      

    And it works now without any problem! It's just amazing!

    ps I decided to write this answer in case it will help someone like me and will save them some time. If you know how to change working directory in XCode 9 for iOS, please, leave me a comment - now I am really curious why I can't find it.

提交回复
热议问题