CringeDB/System Abstraction/linux/cdb_file.c
2022-08-29 17:29:21 +02:00

105 lines
2.1 KiB
C

#include "../cdb_sustem.h"
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/errno.h>
#include <sys/file.h>
#include <fcntl.h>
struct sus_File_impl{
void * memroy;
size_t length;
int fd;
};
sus_File sus_fileOpenInMem(char * fileName, unsigned long parameter) {
int flags = O_RDWR;
if(parameter & SUS_FILE_NEW) flags |= O_CREAT | O_EXCL;
int fd = open(fileName, flags, S_IRWXU);
if(fd == -1) return NULL;
if(flock(fd, LOCK_EX | LOCK_NB)) {
close(fd);
return NULL;
}
struct stat info;
if(stat(fileName, &info)) {
close(fd);
return NULL;
}
if((parameter & SUS_FILE_TEMP) == SUS_FILE_TEMP) unlink(fileName);
if(info.st_size == 0) {
write(fd, "", 1);
info.st_size++;
}
void *mem = mmap(NULL, info.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(mem == MAP_FAILED) {
close(fd);
return NULL;
}
sus_File file = (sus_File) sus_heapAlloc(sizeof(struct sus_File_impl));
file->memroy = mem;
file->length = info.st_size;
file->fd = fd;
return file;
}
void * sus_fileFileToMemroy(sus_File file) {
return file->memroy;
}
sus_Bool sus_fileExists(char * fileName) {
struct stat bro;
return !stat(fileName, &bro);
}
void sus_fileClose(sus_File file) {
if(file->memroy != NULL) {
msync(file->memroy, file->length, MS_SYNC);
munmap(file->memroy, file->length);
close(file->fd);
}
sus_heapFree(file);
}
void sus_fileFlush(sus_File file) {
msync(file->memroy, file->length, MS_SYNC);
}
void * sus_fileResize(sus_File file, signed long appendBytes) {
size_t newSize = file->length + appendBytes;
lseek(file->fd, newSize - 1, SEEK_SET);
write(file->fd, "", 1);
munmap(file->memroy, file->length);
void *newMem = mmap(NULL, newSize, PROT_READ | PROT_WRITE, MAP_SHARED, file->fd, 0);
if(newMem == MAP_FAILED) {
sus_fileClose(file);
file->fd = 0;
file->length = 0;
file->memroy = NULL;
return NULL;
}
file->length = newSize;
file->memroy = newMem;
return newMem;
}
void sus_fileDelete(char * fileName) {
unlink(fileName);
}
void sus_fileRename(char * fileName, char * newFileName) {
link(fileName, newFileName);
unlink(fileName);
}