Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between writing to file atomically and not

What is the difference in writing to files atomically on the iPhone in objective-c and not, is there any performance difference between the two?

like image 485
Mark Szymanski Avatar asked Apr 24 '10 15:04

Mark Szymanski


People also ask

What is file atomic?

An atomic file operation is an operation that cannot be interrupted or "partially" performed. Either the entire operation is performed or the operation fails.

Is write an atomic?

Does that mean write is atomic? Technically, yes: future reads must return the entire contents of the write, or none of it.


2 Answers

Atomic in general means the operation cannot be interrupted will complete or have no effect. When writing files, that is accomplished by writing to a temporary file then replacing the original with the temporary when the write completes.

A crash while writing an atomic file means the original is not modified and there is a garbage file that can be deleted. A crash while writing normally would mean an expected good file is corrupt.

Performance wise the cost is minimal. During the write you will have two copies of a file. The file replace is a very simple operation at the file system level.

Edit: thanks zneak

like image 117
drawnonward Avatar answered Oct 05 '22 16:10

drawnonward


Writing atomically takes more steps - additionally auxiliary file is created. NSString Class Reference explains:

If YES, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the receiver is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.

Here is the example in the case of pLists:

[array writeToFile:path atomically:YES]; 

when "YES", then pList is updated just once even if you run the code several times in XCode,

[array writeToFile:path atomically:NO]; 

when "NO" it is updated as many as you run the same code (repeated update).

like image 33
Darius Miliauskas Avatar answered Oct 05 '22 15:10

Darius Miliauskas