您可以像在 C 中一样使用 FILE*。例如...
- (id)initWithFileUrl:(NSURL *)url
{
if (self = [super init]) {
NSFileManager *fileManager = [[NSFileManager alloc] init];
[fileManager createDirectoryAtPath:[[url path] stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:0];
char const *path = [fileManager fileSystemRepresentationWithPath:url.path];
fp = fopen(path, "a");
if (!fp) {
[NSException raise:@"Can't open file for recording: " format:@"%s", strerror(errno)];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:[UIApplication sharedApplication]];
}
return self;
}
- (void)writeBytes:(void const *)bytes length:(uint32_t)size
{
if (fp && fwrite(bytes, size, 1, fp) != 1) {
[NSException raise:@"File Write Error" format:@"%s", strerror(errno)];
}
}
- (void)writeBytes:(void const *)bytes andSize:(uint32_t)size
{
if (!fp) return;
if (fwrite(&size, sizeof size, 1, fp) != 1 || fwrite(bytes, size, 1, fp) != 1) {
[NSException raise:@"File Write Error" format:@"%s", strerror(errno)];
}
}
- (void)writeInt32:(int32_t)value
{
[self writeBytes:&value length:sizeof value];
}
- (void)writeInt64:(int64_t)value
{
[self writeBytes:&value length:sizeof value];
}
- (void)writeData:(NSData *)data
{
[self writeBytes:data.bytes andSize:data.length];
}
- (void)writeCGFloat:(CGFloat)value
{
[self writeBytes:&value length:sizeof value];
}
- (void)writeCGPoint:(CGPoint)point
{
[self writeBytes:&point length:sizeof(point)];
}