2013-01-16 38 views
0

我想輸出標記爲不同標記名稱的每行,並希望將每個標記保存在文件中。我可以寫這個文件,但是它寫完了。我如何將每一行寫入不同的文件?XML標記xcode保存文件

輸入:

英語泰坦尼克號
leondradicapro凱特

德國酒店hüßßan
tomhanks angleina

輸出:

<language>english<language/> 
<movie>titanic<movie/> 
<Actor>leondradiacpro<Actor/> 
<Actress>kate<Actress/> 

<language>German<language/> 
... 

代碼:

for (NSString *str in lineFile) 

       { 

        if([str hasPrefix:@"english "]) 
        { 

         NSMutableArray *dd = [[NSMutableArray alloc] initWithArray:[[str stringByReplacingOccurrencesOfString:@"english" withString:@""] componentsSeparatedByString:@" "]]; 

        NSArray *tag = [NSArray aarrayWithObjects:@"er",@"langauge",@"movie",@"actor",@"kate",nil]; 

        NSMutableString *output =[[NSMutableString alloc] init]; 
        NSUInteger tagindex =0; 

        for (NSString *words in word) 

        { 
         if(tagindex >=[tag count]) 
         { 

          NSLog(@"dad"); 
          break; 
        } 
         [output appendFormat:@"<%@>%@<%@>\n", [tag objectAtIndex:tagindex],words,[tag objectAtIndex:tagindex]]; 
         NSLog(@"%@",output); 
[output writeToFile:@"/Users/xx/Desktop/homework.txt" atomically:YES encoding:NSASCIIStringEncoding error:NULL];  
         tagindex++; 

現在我可以能夠只讀的語言和電影(1號線),我怎麼可以添加你需要編寫與C方法文件第二行和標籤也

回答

0

,也許以下方法可以幫到你

-(void)writeToFile:(NSString *)str:(NSString *) fileName 
{ 
    NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding]; 
    NSString *filePath=[NSString stringWithFormat:@"%@",fileName]; 
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO){ 
     NSLog(@"file not exist,create it..."); 
     [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]; 
    }else { 
       NSLog(@"file exist!!!"); 
    } 

    FILE *file = fopen([filePath UTF8String], [@"ab+" UTF8String]); 

    if(file != NULL){ 
     fseek(file, 0, SEEK_END); 
    } 
    int readSize = [data length]; 
    fwrite((const void *)[data bytes], readSize, 1, file); 
    fclose(file); 
}