2012-03-02 29 views
9

Tôi tìm thấy mã bên dưới để xóa tệp trong mục tiêu-c, nhưng tôi muốn chỉ xóa tất cả các tệp trong thư mục Caches và giữ thư mục Caches chinh no.Mục tiêu c: Làm thế nào để chỉ xóa tất cả tập tin trong một thư mục nhưng giữ cho chính thư mục

Ai đó có thể đề xuất phương pháp để làm điều đó?

Cảm ơn

NSFileManager *filemgr; 

filemgr = [NSFileManager defaultManager]; 

if ([filemgr removeItemAtPath: [NSHomeDirectory() stringByAppendingString:@"/Library/Caches"] error: NULL] == YES) 
     NSLog (@"Remove successful"); 
else 
     NSLog (@"Remove failed"); 

CẬP NHẬT

NSFileManager *filemgr; 

filemgr = [NSFileManager defaultManager]; 

if ([filemgr removeItemAtPath: [NSHomeDirectory() stringByAppendingString:@"/Library/Caches"] error: NULL] == YES) 
    NSLog (@"Remove successful"); 
else 
    NSLog (@"Remove failed"); 

[filemgr createDirectoryAtPath: [NSHomeDirectory() stringByAppendingString:@"/Library/Caches"] withIntermediateDirectories:NO attributes:nil error:nil]; 
+0

Làm thế nào về tái tạo thư mục Caches sau khi xóa? – ohho

+0

Bạn có thể xóa thư mục và sau đó tạo lại thư mục, mặc dù bạn phải đảm bảo rằng bạn duy trì quyền chính xác. – dreamlax

+0

Ý tưởng hay, cảm ơn –

Trả lời

39

Vòng qua các tập tin trong thư mục đó.

NSFileManager *fileMgr = [NSFileManager defaultManager]; 
NSArray *fileArray = [fileMgr contentsOfDirectoryAtPath:directory error:nil]; 
for (NSString *filename in fileArray) { 

    [fileMgr removeItemAtPath:[directory stringByAppendingPathComponent:filename] error:NULL]; 
} 
+0

Cảm ơn bạn đã đề xuất nhưng đã gặp lỗi khi biên soạn chương trình. 'Chủ đề 1: EXC_BAD_ACCESS (mã = 1, địa chỉ = 0x8b8c0001)' –

+0

Trong dòng nào nó cho thấy lỗi? , gỡ lỗi mã và nói. – HarshIT

+0

Sai lầm của tôi, tên tệp chỉ là tên, phải nối thêm thư mục để lấy đường dẫn đầy đủ – Hanon

0
- (void) removeDocuments 
{ 
    NSString *docDir = // get documents directory 
    NSString *cacheDir = [docDir stringByAppendingPathComponent: @"cacheDir"]; 

    // check if cache dir exists 

    // get all files in this directory 
    NSFileManager *fm = [NSFileManager defaultManager]; 
    NSArray *fileList = [fm contentsOfDirectoryAtPath: cacheDir error: nil]; 

    // remove 
    for(NSInteger i = 0; i < [fileList count]; ++i) 
    { 
     NSString *fp = [fileList objectAtIndex: i]; 
     NSString *remPath = [cacheDir stringByAppendingPathComponent: fp]; 
     [fm removeItemAtPath: remPath error: nil]; 
    } 
} 
Các vấn đề liên quan