1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Reading from a file in Obj-C

Discussion in 'Mac Programming' started by MacFan26, Nov 4, 2007.

  1. macrumors 65816

    MacFan26

    #1
    Anyone know the best way to read text from a simple .txt file and store it in an NSString? I'm trying to do it like this:

    NSString *data = [[NSString alloc] initWithContentsOfFile:mad:"data.txt"];

    The data.txt file is in the same source folder as this code. I want to do something similar to reading from a file using Java's Scanner. Thanks for any help!
     
  2. macrumors 68030

    Catfish_Man

    #2
    You need to use the correct path. Putting it in the same folder as the source won't make it end up in the application at all.
     
  3. macrumors 65816

    MacFan26

    #3
    So, for a correct path, do I need something more than "./data.txt" ?

    I'm using this to create my images, and it works just fine because they are in my resources folder for the project.

    one = [NSImage imageNamed:mad:"one.jpg"];
     
  4. macrumors 68000

    GeeYouEye

    #4
    *grumble*

    Your current working directory varies with build style, settings, read/write, and phase of the moon. Provide an "Open..." dialog, or else use a semi-hardcoded path (using NSHomeDirectory() if necessary).

    EDIT: oh, they're in your Resources folder? Read up on NSBundle.
     
  5. macrumors 68030

    Catfish_Man

    #5
    Indeed. NSBundle is your best friend for easy access to resources :)
     
  6. macrumors 65816

    MacFan26

    #6
    Yeah this was for a very simple program where I just wanted to read input from one file. Thanks for letting me know about NSBundle. For now, I guess in XCode if you store something in the resources folder you need to go up two directories from your source to access it, this works fine for me:

    NSString *data = [[NSString alloc] initWithContentsOfFile:mad:"../../data.txt"];


    Sorry for the newbiness, I'm just asking..
     
  7. macrumors 601

    HiRez

    #7
    Just use mainBundle: and pathToResource: and it'll take care of finding it for you.

    Code:
    NSString *fileContents = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathToResource:"data" ofType:"txt"]];
     

Share This Page