Overwriting a file programmatically in Cocoa

This code copies the specified file and places it in the Docs directory. I am trying to create a simple backup solution. The problem is that this operation does not overwrite the existing file if the operation is repeated.

Two questions:

What is the best way to rewrite in code?

How difficult would it be to add the current date to each copied file? In this case, the rewrite operation will not be performed. This would be much more useful for storing incremental backups. If I decided to do it this way, I realized that I would need to create a new path so that everything was organized.

Thanks.

Floor

NSString * name = @"testFile"; NSArray * files = [NSArray arrayWithObject: name]; NSWorkspace * ws = [NSWorkspace sharedWorkspace]; [ws performFileOperation: NSWorkspaceCopyOperation source: @"~/Library/Application Support/testApp" destination: @"~/Documents/" files: files tag: 0]; 
+4
source share
1 answer

You can try using NSFileManager, example below (untested):

 // Better way to get the Application Support Directory, similar method for Documents Directory - (NSString *)applicationSupportDirectory { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory(); return [basePath stringByAppendingPathComponent:@"testApp"]; } - (void) removeFile { NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *applicationSupportDirectory = [self applicationSupportDirectory]; NSError *error = nil; NSString* filePath = [applicationSupportDirectory stringByAppendingPathComponent: @"testFile"]; if ([fileManager fileExistsAtPath:filePath isDirectory:NULL]) { [fileManager removeItemAtPath:filePath error:&error]; } } 

Edit: Take a look at the NSFileManager class description for other functions that might be useful (for your second question).

+2
source

Source: https://habr.com/ru/post/1338947/


All Articles