On 9/25/20 8:24 AM, Daniel P. Berrangé wrote:
This code:
fd = os.open(pathname, os.O_RDWR | os.O_CREAT, 0o666)
f = open(fd, 'r+', encoding='utf-8')
This was my best attempt to open the file read/write, creating it if it
doesn't exist.
Plain
f = open(pathname, "r+", encoding='utf-8')
fails instead of creates, and
Checking what POSIX says for fopen():
https://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html
Yep, "r+" does not use O_CREAT.
f = open(pathname, "w+", encoding='utf-8')
truncates.
Yep, "w+" uses O_TRUNC.
If you know a better way, tell me!
IIUC, you need "a+" as the mode, rather than "w+"
That uses O_APPEND. Which is fine if you are only appending and not
touching existing contents, but not what you want if you are doing
random access.
Yeah, the fopen() interface is rather puny, in that it does not express
as many modes as open() supports.
--
Eric Blake, Principal Software Engineer
Red Hat, Inc. +1-919-301-3226
Virtualization: qemu.org | libvirt.org