Add file module with calls for daily file operations

This commit is contained in:
Ilja Kartašov 2019-06-28 15:58:01 +02:00
parent 0d6fca9b26
commit 4ba00ca17a
2 changed files with 120 additions and 0 deletions

85
file.c Normal file
View File

@ -0,0 +1,85 @@
/******************************************************************************
*
* Copyright (c) 2017-2019 by Löwenware Ltd
* Please, refer LICENSE file for legal information
*
******************************************************************************/
/**
* @file file.c
* @author Ilja Kartašov <ik@lowenware.com>
* @brief
*
* @see https://lowenware.com/
*/
#include <stdio.h>
#include <sys/sendfile.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include "file.h"
bool
cstuff_file_exists(const char *file)
{
return ( access( file, F_OK ) != -1 ) ? true : false;
}
CStuffRetcode
cstuff_file_copy(const char *src, const char *dest)
{
CStuffRetcode rc = CSTUFF_SYSCALL_ERROR;
int fd_src = open(src, O_RDWR), fd_dest, len;
struct stat src_stat;
if (!(fd_src < 0)) {
if (lockf(fd_src, F_LOCK, 0) != -1) {
if (!stat(src, &src_stat)) {
fd_dest = open(dest, O_CREAT | O_WRONLY | O_TRUNC);
if (!(fd_dest < 0)) {
len = sendfile(fd_dest, fd_src, NULL, src_stat.st_size);
if (len == src_stat.st_size) {
rc = CSTUFF_SUCCESS;
} else {
fprintf(stderr, "sendfile error (%d != %d): %s\n", len,
(int)src_stat.st_size, strerror(errno));
}
close(fd_dest);
} else {
fprintf(stderr, "dest open() error\n");
}
} else {
fprintf(stderr, "src stat() error\n");
}
if (lockf(fd_src, F_TEST, 0) == 0){
lockf(fd_src, F_ULOCK, 0);
}
} else {
fprintf(stderr, "src lockf() error\n");
}
close(fd_src);
} else {
fprintf(stderr, "src open() error\n");
}
return rc;
}
CStuffRetcode
cstuff_file_move(const char *src, const char *dest)
{
CStuffRetcode rc;
if (!(rc = cstuff_file_copy(src, dest))) {
if (unlink(src) != 0)
return CSTUFF_SYSCALL_ERROR;
}
return rc;
}

35
file.h Normal file
View File

@ -0,0 +1,35 @@
/******************************************************************************
*
* Copyright (c) 2017-2019 by Löwenware Ltd
* Please, refer LICENSE file for legal information
*
******************************************************************************/
/**
* @file file.h
* @author Ilja Kartašov <ik@lowenware.com>
* @brief
*
* @see https://lowenware.com/
*/
#ifndef CSTUFF_FILE_H_3C3D5EDC_A624_4550_98A4_29AD5A41301D
#define CSTUFF_FILE_H_3C3D5EDC_A624_4550_98A4_29AD5A41301D
#include <stdbool.h>
#include "retcode.h"
bool
cstuff_file_exists(const char *file);
CStuffRetcode
cstuff_file_copy(const char *src, const char *dest);
CStuffRetcode
cstuff_file_move(const char *src, const char *dest);
#endif /* !FILE_H */