背景,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);

}


Logo

更多推荐