domlao
domlao

Reputation: 16029

Accessing data files in Objective-C or cocoa

I am fairly new to a objective-c or in whole mac/iphone development. My question is how can I acces a data files(text files or flat files) in objective-c? For example I have a sample.txt file, how can I open this files and access its data? Do I need to use a class? And I heard about dictionary, is this term related to my problems?

Please kindly redirect me to a good site.

Thanks alot.

sasayins.

Upvotes: 0

Views: 570

Answers (1)

dreamlax
dreamlax

Reputation: 95365

You can use regular fopen and fread to access the contents of a file. Alternatively, you can use NSString if your file contains only text or NSData for non-text data.

NSString *myString = [NSString stringWithContentsOfFile:@"/path/to/file"];

NSData *myData = [NSData dataWithContentsOfFile:@"/path/to/file"];

Edit

@"/path/to/file" a constant “Objective-C” style string. It is different to a regular C string (i.e. without the @ prepended) because it behaves like an object; you can send it messages, and it is able to be stored in NSArrays etc. From a Mac Programmer's point of view, these Objective-C strings can be treated just like NSString objects.

The Mac OS X filesystem layout typically looks like this:

    /System          contains system files similar to C:\windows\
    /Library         contains libraries, similar to C:\windows\system32\
    /Users           similar to Windows' C:\Documents and Settings\
    /Applications    Mac's version of C:\Program Files\
    /Developer       Where Xcode, SDKs, and other developer tools live.

If your username on your Mac is "smith", then your Home directory is /Users/smith. If you have a file in your Documents folder of your Home directory called data.txt, then you can use the following code to access it (but I wouldn't recommend hard-coding paths like this)

NSString *myString = [NSString stringWithContentsOfFile:@"/Users/smith/Documents/data.txt"];

There are various functions available for reliably obtaining your home directory and other directories of particular interest. The NSString documentation explains the various methods available for manipulating strings containing paths.

Upvotes: 2

Related Questions