Replace FWRITE with a function
In a few places we use the FWRITE() macro to open a file, replace it's contents with a given string and close it again. There's no real reason this needs to be a macro rather than just a function though. Turn it into a function 'write_file()' and make some ancillary cleanups while we're there: - Add a return code so the caller can handle giving a useful error message - Handle the case of short write()s (unlikely, but possible) - Add O_TRUNC, to make sure we replace the existing contents entirely Signed-off-by: David Gibson <david@gibson.dropbear.id.au> Signed-off-by: Stefano Brivio <sbrivio@redhat.com>
This commit is contained in:

committed by
Stefano Brivio

parent
096e48669b
commit
ea5936dd3f
33
util.c
33
util.c
@@ -449,3 +449,36 @@ int fls(unsigned long x)
|
||||
|
||||
return y;
|
||||
}
|
||||
|
||||
/**
|
||||
* write_file() - Replace contents of file with a string
|
||||
* @path: File to write
|
||||
* @buf: String to write
|
||||
*
|
||||
* Return: 0 on success, -1 on any error
|
||||
*/
|
||||
int write_file(const char *path, const char *buf)
|
||||
{
|
||||
int fd = open(path, O_WRONLY | O_TRUNC | O_CLOEXEC);
|
||||
size_t len = strlen(buf);
|
||||
|
||||
if (fd < 0) {
|
||||
warn("Could not open %s: %s", path, strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
|
||||
while (len) {
|
||||
ssize_t rc = write(fd, buf, len);
|
||||
|
||||
if (rc <= 0) {
|
||||
warn("Couldn't write to %s: %s", path, strerror(errno));
|
||||
break;
|
||||
}
|
||||
|
||||
buf += rc;
|
||||
len -= rc;
|
||||
}
|
||||
|
||||
close(fd);
|
||||
return len == 0 ? 0 : -1;
|
||||
}
|
||||
|
Reference in New Issue
Block a user