简体   繁体   中英

How to write lines to a file, and each line is a atomic operation?

I want to write some lines to a file, and I need each line of writing is a atomic operation.

For example, I have 3 lines:

111111111111111111111111
222222222222222222222222
333333333333333333333333

When I write them into a file line by line, the program may be exit by error, so the saved data may be:

11111111111111111111111
222222

This is not what I expected. I hope each line is a transaction, a atomic operation.

How should I do this?


Currently I use Java to do this.

There isn't a 100% reliable way to guarantee this.

I think the closest you can get is by calling flush() on the output stream and then sync() on the underlying file descriptor. Again, there are failure modes where this won't help.

If you really need atomic writing of new lines to a file, I guess the only way is to create a copy under a new name, write the new line and rename the new file to the original name. The rename operation is atomic, at least under POSIX. On Windows you would need to remove the original file before renaming, which bears the problem of not being able to restore the file if a problem occurs in the that process.

You can use flush/sync as @aix suggests. Otherwise (and better -- 99.999% reliable) is to use some sort of environment (such as a database) that includes transaction support and use commit .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM