James (MrGeckosMedia.com), joined by, Noah (RockntheSweater.com), and Karl, explains how file managing works in c and cocoa.
7:49
Example code from episode.
Files C Example
#import
BOOL file_exist(const char *fileName) {
FILE *file = fopen(fileName, "r");
if (file) {
fclose(file);
return YES;
}
return NO;
}
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
const char *ourFile = [[@"~/Desktop/file.txt" stringByExpandingTildeInPath] UTF8String];
FILE *file;
if (!file_exist(ourFile)) {
file = fopen(ourFile, "w");
time_t currTime = time(NULL);
fprintf(file, "%s: We just made this file.\n", ctime(&currTime));
} else {
file = fopen(ourFile, "a");
}
time_t currTime = time(NULL);
fprintf(file, "%s: Here is a new line in this file.\n", ctime(&currTime));
fclose(file);
[pool drain];
return 0;
}
Files Cocoa Exmaple
#import
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSFileManager *manager = [NSFileManager defaultManager];
NSString *ourFile = [@"~/Desktop/file.txt" stringByExpandingTildeInPath];
NSFileHandle *file;
if (![manager fileExistsAtPath:ourFile]) {
[manager createFileAtPath:ourFile contents:nil attributes:nil];
file = [NSFileHandle fileHandleForWritingAtPath:ourFile];
[file writeData:[[NSString stringWithFormat:@"%@: Here is a new file.\n", [NSDate date]] dataUsingEncoding:NSUTF8StringEncoding]];
} else {
file = [NSFileHandle fileHandleForWritingAtPath:ourFile];
[file seekToEndOfFile];
}
[file writeData:[[NSString stringWithFormat:@"%@: Here is a new line.\n", [NSDate date]] dataUsingEncoding:NSUTF8StringEncoding]];
[file closeFile];
[pool drain];
return 0;
}
Keynote used in this Episode
Keynote in PDF Format