iOS本機存放區--c語言方式例子

來源:互聯網
上載者:User

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

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.