Utils: new function to copy the content of a file into another file

This commit is contained in:
Celine Mercier
2017-08-03 16:28:54 +02:00
parent 344566d9e9
commit 927c684fc2
2 changed files with 74 additions and 0 deletions

View File

@ -36,6 +36,66 @@
**********************************************************************/
int copy_file(const char* src_file_path, const char* dest_file_path)
{
int src_fd, dst_fd, n, err;
unsigned char buffer[4096];
src_fd = open(src_file_path, O_RDONLY);
if (src_fd == -1)
{
obi_set_errno(OBI_UTILS_ERROR);
obidebug(1, "\nError opening a file to copy");
return -1;
}
dst_fd = open(dest_file_path, O_CREAT | O_WRONLY, 0777); // overwrite if already exists
if (dst_fd == -1)
{
obi_set_errno(OBI_UTILS_ERROR);
obidebug(1, "\nError opening a file to write a copy: %s", dest_file_path);
return -1;
}
while (1)
{
err = read(src_fd, buffer, 4096);
if (err == -1)
{
obi_set_errno(OBI_UTILS_ERROR);
obidebug(1, "\nProblem reading a file to copy");
return -1;
}
n = err;
if (n == 0)
break;
err = write(dst_fd, buffer, n);
if (err == -1)
{
obi_set_errno(OBI_UTILS_ERROR);
obidebug(1, "\nProblem writing to a file while copying");
return -1;
}
}
if (close(src_fd) < 0)
{
obi_set_errno(OBI_UTILS_ERROR);
obidebug(1, "\nError closing a file after copying it");
return -1;
}
if (close(dst_fd) < 0)
{
obi_set_errno(OBI_UTILS_ERROR);
obidebug(1, "\nError closing a file after copying to it");
return -1;
}
return 0;
}
int digit_count(index_t i)
{
int n_digits;