2011-08-12 19 views
10

के लिए स्थानीय संसाधन txt फ़ाइल में स्ट्रिंग को कैसे संलग्न करें मैं स्थानीय संसाधन फ़ाइल में तार जोड़ने की कोशिश कर रहा हूं लेकिन मुझे समाधान खोजने में परेशानी हो रही है। मैं अपने आवेदन में सभी फ़ंक्शन कॉल के लिए लॉग फ़ाइल बनाने की कोशिश कर रहा हूं, इसलिए यदि यह क्रैश हो तो मैं देख सकता हूं कि यह किस फ़ंक्शन पर रुक गया है।आईओएस एसडीके

मैंने एक log.rtf फ़ाइल बनाई है, लेकिन मैं इस फ़ाइल में लिखने में सक्षम नहीं हूं। क्या कोई मेरी पूरी चीज़ को ओवरराइट किए बिना इस फाइल में स्ट्रिंग को जोड़ने में मदद कर सकता है?

उत्तर

31

मैंने उपरोक्त समस्या के लिए निम्नलिखित कोड का उपयोग किया है।

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDir = [documentPaths objectAtIndex:0]; 
NSString *logPath = [[NSString alloc] initWithFormat:@"%@",[documentsDir stringByAppendingPathComponent:@"log.rtf"]]; 
NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:logPath]; 
[fileHandler seekToEndOfFile]; 
[fileHandler writeData:[text dataUsingEncoding:NSUTF8StringEncoding]]; 
[fileHandler closeFile]; 
0
- (void)log:(NSString *)message { 
    NSMutableString *string = [[NSMutableString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/log.txt", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]]]; 
    if (!string) string = [[NSMutableString alloc] init]; 
    [string appendFormat:@"%@\r\n", message]; 
    [string writeToFile:[NSString stringWithFormat:@"%@/log.txt", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] atomically:YES encoding:NSUTF8StringEncoding error:nil]; 
} 
+0

@ टिम, XCode 4.1 –

+0

से हटा दिया गया है मैं अपने कोड अद्यतन =)! – elslooo

+1

यदि फ़ाइल का आकार 10k से ऊपर है तो क्या होगा। फिर परिवर्तनीय स्ट्रिंग इस डेटा को अधिक नहीं रख सकती है, तो यह ऐप क्रैश का कारण बन जाएगी। कृपया इसे आज़माएं और मुझे बताएं। एक txt दस्तावेज़ ले लो। 10k आकार के साथ और इस कोड का उपयोग कर एक लाइन जोड़ने की कोशिश करें। –

0

इस तरह आप इस 'writeToFile: atomically:' क्या कर सकते हैं ..

+ (void)WriteLogWithString:(NSString *)log 
{ 

     if(log != nil){ 

      NSString *locationFilePath = [self getLogFilePath];//access the path of file 

      FILE *fp = fopen([locationFilePath UTF8String], "a"); 

      fprintf(fp,"%s\n", [log UTF8String]); 

      fclose(fp); 
     } 

} 
+0

धन्यवाद सचिन, लेकिन यह फ़ाइल के अंत में नहीं, आपकी फ़ाइल शुरू करने के लिए जोड़ देगा। –

संबंधित मुद्दे