- #import <Foundation/Foundation.h>
- // 定义一个Scores结构体
- typedef struct {
- double mathScore,engScore,cScore;
- } Scores;
- NSString * NSStringFromScores(Scores s);
- int main(int argc, const char * argv[])
- {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- NSFileManager *fm=[NSFileManager defaultManager];
-
- NSString * aryPath= @"C:/Users/Administrator/Desktop/ary.xml";
- NSString * dictPath= @"C:/Users/Administrator/Desktop/dict.xml";
-
- // *1> OC数组的读写文件操作
- NSArray *sary= [NSArray arrayWithObjects:@"Jack",@"Tommy",@"Bolt",nil];
- BOOL aryFlag=[sary writeToFile:aryPath atomically:YES];
- if(aryFlag)
- {
- sary=[NSArray arrayWithContentsOfFile:aryPath];
- NSLog(@"\naryFromFile=\n%@",sary);
- }
-
- // *2> OC字典的读写文件操作
- NSMutableDictionary * dict = [NSMutableDictionary dictionary];
- [dict setValue:sary forKey:@"ary"];
- [dict setValue:aryPath forKey:@"aryPath"];
- BOOL dictFlag=[dict writeToFile:dictPath atomically:YES];
- if(dictFlag)
- {
- dict=[NSMutableDictionary dictionaryWithContentsOfFile:dictPath];
- NSLog(@"\ndictFromFile=\n%@",dict);
- }
-
-
- // *3> OCstr的序列化与反序列化
- NSString * path= @"C:/Users/Administrator/Desktop/str.txt";
- // 将OCstr按某种编码方式encode成bytes保存在NSData
- NSData *data=[@"this is an NSData test!!\n" dataUsingEncoding:NSUTF8StringEncoding];
- // 将bytes写入文件
- BOOL strPathFlag=[fm createFileAtPath:path contents:data attributes:nil];
- if(strPathFlag)
- {
- // 从文件读取bytes保存为NSData类型
- NSData *strData=[fm contentsAtPath:path];
- // 将bytes按某种解码方式decode成OCstr
- NSString *strFromData=[[[NSString alloc] initWithData:strData
- encoding:NSUTF8StringEncoding] autorelease];
- NSLog(@"\nstrFromData=%@",strFromData);
- }
-
-
-
- // *4> struct与NSValue的互相转换
- Scores scores1={66.0,77.0,88.0},scores2={0},* scores3={0};
- // 将struct包装成NSValue,@encode(Type)将struct类型转换成(char *)类型
- NSValue *scoresVal=[NSValue valueWithBytes:&scores1 objCType:@encode(Scores)];
- // 从NSValue中取出struct
- [scoresVal getValue:&scores2];
- NSLog(@"\nscoresValFromStruct=%@\nscores2FromNSValue=%@",scoresVal,NSStringFromScores(scores2));
-
-
- // *5> 将数据按照其在内存中的bytes写入文件,并将文件中的bytes读入内存
- NSString * bytePath= @"C:/Users/Administrator/Desktop/byte.txt";
- // 将struct按照其内存中的bytes保存到NSData对象
- NSData *data2=[NSData dataWithBytes:&scores2 length:sizeof(Scores)];
- // 将bytes写入文件
- BOOL bytePathFlag=[fm createFileAtPath:bytePath contents:data2 attributes:nil];
- if(bytePathFlag)
- {
- // 从文件读取bytes保存到NSData对象
- NSData *data3=[fm contentsAtPath:bytePath];
- // 取出NSData对象中的bytes,转换成struct
- scores3=(Scores *)[data2 bytes];
- NSLog(@"\nscores3FromNSData=%@",NSStringFromScores(*scores3));
- }
-
-
- [pool drain];
- return 0;
- }
- // 将Scores结构体转字符串
- NSString * NSStringFromScores(Scores s)
- {
- return [NSString stringWithFormat:
- @"{ mathScore=%.2f, engScore=%.2f, cScore=%.2f }",
- s.mathScore,s.engScore,s.cScore];
- }
复制代码
|
|