背景,iOS其實和Mac的系統是一脈相承,而它們其實是unix的核心,所以你在unix(linux)上面可以使用的api,在這裡也是可以用的。
很多時候,我們需要儲存一些資訊在本地,iOS SDK提供了很好的介面支援,但是有時候,我們可能需要使用標準C的方式存取檔案,下面就是這樣的方式,我這裡就不多解釋了,
//這個函數得到存取的路徑。
- (char*)makePreferencesFilename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"backup.dat"];
int len = [writablePath length];
char *filename = (char*)malloc(sizeof(char)
* (len + 1));
[writablePath getCString:filename maxLength:len + 1 encoding:[NSString defaultCStringEncoding]];
return filename;
}
- (void)saveOptions
{
char *path = [self makePreferencesFilename];
FILE *fp = fopen(path,
"wt");
char sTemp [100];
//snprintf(sTemp, [loginName length], "%s", [loginName UTF8String]);
fputs([loginName UTF8String], fp);
fputs("\n", fp);
if(bSavePassword) {
//snprintf(sTemp, [loginPassword length], "%s", [loginPassword UTF8String]);
fputs([loginPassword UTF8String], fp);
}
else {
fputs("", fp);
}
fputs("\n", fp);
//存其他的資訊
fclose(fp);
free(path);
}
- (void)loadOptions
{
char *path = [self makePreferencesFilename];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *spath = [[NSString alloc] initWithFormat:@"%s", path];
BOOL fileExists = [fileManager fileExistsAtPath:spath];
if (!fileExists)
{
loginName =
nil;
loginPassword =
nil;
//初始化其他的資訊。
free(path);
[spath release];
return;
}
char sTemp[100];
FILE *fp = fopen(path,
"rt");
//fscanf(fp, "%s", sTemp);
fgets(sTemp, 100,fp);
int ilen = strlen(sTemp);
sTemp[ilen - 1] = 0;
loginName = [[NSString alloc] initWithFormat:@"%s",sTemp];
if([loginName isEqualToString:@"(null)"]) {
[loginName release];
loginName =
nil;
}
if(sTemp[0] == 0){
[loginName release];
loginName =
nil;
}
fgets(sTemp, 100,fp);
ilen = strlen(sTemp);
sTemp[ilen - 1] = 0;
loginPassword = [[NSString alloc] initWithFormat:@"%s",sTemp];
if([loginPassword isEqualToString:@"(null)"]) {
[loginPassword release];
loginPassword =
nil;
}
if(sTemp[0] == 0){
[loginPassword release];
loginPassword =
nil;
}
//讀其他的資訊
fclose(fp);
[spath release];
free(path);
}