[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: file programming in the Gnustep framework
From: |
Richard Frith-Macdonald |
Subject: |
Re: file programming in the Gnustep framework |
Date: |
Tue, 1 Jan 2008 17:39:47 +0000 |
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On 1 Jan 2008, at 15:13, Arno R. Schleich wrote:
Hi,
I am just starting to use the framework. I am looking for some
tutorial
like stuff on file I/O in GNUStep. Is it advisable not to use "lower
level" constructs such as fprintf etc at all ? From reading the online
documentation for file handle/ file manager I could not figure out how
to perform a trivial task like reading a variable length file of real
numbers. Any hints where I would find some beginner's
examples/instructions regarding file I/O ?
You should probably use NSFileManager to manage files (listing,
moving, deleting etc).
For low level I/O you would use NSFileHandle or NSStream.
For instance, to read the variable length file you could do the job
in two lines ...
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtpath:
@"myfile"];
NSData *contents = [handle readDataToEndOfFile];
That being said, you might do it in one line with:
NSData *contents = [NSData dataWithContentsOfFile: @"myfile"];
If you want to read the file a bit at a time ...
NSInputStream *istream = [NSInputStream inputStreamWithFileAtPath:
@"myfile"];
double number;
while ([istream read: (uint8_t*)&number maxLength: sizeof(number)] ==
sizeof(number))
{
// do something with each number here.
}
For portability, you would want the numbers to be stored in a
standard byte ordering, so you would use NSSwapBigDoubleToHost() to
convert from network byte ordering to host byte ordering.
Of course, you might not want to do this sort of low-level stuff, but
rather work with objects serialised to file.
I suggest looking at property-list objects (NSString, NSNumber,
NSArray, NSDictionary, NSData, NSDate) as combinations of these
objects can be written to or read from file as a single operation
(eg. write an array of numbers by using the -writeToFile:atomically:
method and read it back using [NSArray arrayWithContentsOfFile:
@"afile"]) as these are great for a huge variety of applications.
To deal with complex groupings of arbitrary objects I'd recommend
using NSKeyedArchiver or NSKeyedUnarchiver
For the equivalent of printf/scanf you would normally be appending to
a mutable string (using appendFormat:) or scanning a string (using
the NSScanner class) and using the -writeToFile:atomically: and
stringWithContentsOfFile: methods to perform the file I/O (or
converting the string to an NSData object and using NSFileHandle or
NSStream if you want to send it over a network connection).
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (Darwin)
iD8DBQFHenruSZ/wVHjv7MIRAhW7AKD4ksuNjgOL5wLDLNYhk+z1XEYq6wCdHglu
oIpOcC3oXn5cW/0MlRRHovY=
=+x2q
-----END PGP SIGNATURE-----