Reading from a file in Obj-C

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

  1. macrumors 65816

    MacFan26

    Joined:
    Jan 8, 2003
    Location:
    San Jose, California
    #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

    Joined:
    Sep 13, 2001
    Location:
    Portland, OR
    #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. thread starter macrumors 65816

    MacFan26

    Joined:
    Jan 8, 2003
    Location:
    San Jose, California
    #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

    Joined:
    Dec 9, 2001
    Location:
    State of Denial
    #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

    Joined:
    Sep 13, 2001
    Location:
    Portland, OR
    #5
    Indeed. NSBundle is your best friend for easy access to resources :)
     
  6. thread starter macrumors 65816

    MacFan26

    Joined:
    Jan 8, 2003
    Location:
    San Jose, California
    #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

    Joined:
    Jan 6, 2004
    Location:
    Western US
    #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