76 lines
1.4 KiB
C
76 lines
1.4 KiB
C
#include <err.h>
|
|
#include <errno.h>
|
|
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
|
|
#include "util.h"
|
|
|
|
void
|
|
copyFile(const char *source, const char *dest)
|
|
{
|
|
char buffer[1024];
|
|
ssize_t ret;
|
|
int s, d;
|
|
|
|
if ((s = open(source, O_RDONLY)) == -1)
|
|
err(1, "cannot open %s", source);
|
|
if ((d = open(dest, O_WRONLY | O_CREAT, 0644)) == -1)
|
|
err(1, "cannot open %s", dest);
|
|
|
|
while ((ret = read(s, &buffer, 1024)) > 0) {
|
|
write(d, buffer, ret);
|
|
}
|
|
|
|
if (ret == -1)
|
|
err(1, "cannot read from %s", source);
|
|
|
|
close(s);
|
|
close(d);
|
|
}
|
|
|
|
void
|
|
changeDirectory(const char *path)
|
|
{
|
|
if (chdir(path) == -1)
|
|
err(1, "cd '%s'", path);
|
|
}
|
|
|
|
bool
|
|
exists(const char *path)
|
|
{
|
|
if (open(path, O_RDONLY) == -1) {
|
|
if (errno == ENOENT)
|
|
return 0;
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
/*
|
|
* Copy string src to buffer dst of size dsize. At most dsize-1
|
|
* chars will be copied. Always NUL terminates (unless dsize == 0).
|
|
* Returns strlen(src); if retval >= dsize, truncation occurred.
|
|
*/
|
|
size_t
|
|
strbcpy(char *dst, const char *src, size_t dsize)
|
|
{
|
|
const char *osrc = src;
|
|
size_t nleft = dsize;
|
|
|
|
/* Copy as many bytes as will fit. */
|
|
if (nleft != 0) {
|
|
while (--nleft != 0) {
|
|
if ((*dst++ = *src++) == '\0')
|
|
break;
|
|
}
|
|
}
|
|
|
|
/* Not enough room in dst, add NUL and traverse rest of src. */
|
|
if (nleft == 0) {
|
|
if (dsize != 0)
|
|
*dst = '\0'; /* NUL-terminate dst */
|
|
while (*src++)
|
|
;
|
|
}
|
|
|
|
return (src - osrc - 1); /* count does not include NUL */
|
|
}
|