Skip to content

Instantly share code, notes, and snippets.

@tripulse
Last active December 10, 2018 13:41
Show Gist options
  • Save tripulse/0c8cec88f7019c0b15327c69ff2abab9 to your computer and use it in GitHub Desktop.
Save tripulse/0c8cec88f7019c0b15327c69ff2abab9 to your computer and use it in GitHub Desktop.
Little POSIX I/O library
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
/* Buffer structure */
typedef structure
{
void* memory;
int64_t size;
int64_t nmemb;
}
buffer_t;
/* POSIX based file structure */
typedef struct
{
int32_t fd;
int64_t position;
buffer_t buffer;
}
file_t;
int file_open(file_t* file, const char* filename, int permissions)
{
if(file != NULL) return EPERM;
// NOTE: We don't need to cast in C but in C++ we need.
file = (file_t*)malloc(sizeof(file_t));
if(file == NULL) return ENOMEM;
file->fd = (int32_t)open(filename, permissions);
/* If descriptor goes down '0' then I/O error happens */
if(file->fd < 0) return EIO;
file->position = (int)lseek(fd, 0, SEEK_CUR);
if(file->position < 0) return ESPIPE;
}
int file_close(file_t* file)
{
/* If the struct exists or not */
if(file == NULL) return EPERM;
/* Memory previously allocated or not. We can't pass NULL to free() */
if(file->buffer->memory == NULL) return EPERM;
free(file->buffer->memory);
free(file);
}
// NOTE: you need add 'fcntl.h' in your code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment