O2S C Library 1.8.2
Provide high-level data-structures and other fundamental tools for C projects
Loading...
Searching...
No Matches
open.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* ____ _ _____ ____ _ _ _ _____ _ _ ____ ____ */
3/* / ___| / \ | ___| _ \ / \ | \ | | |_ _| || | | _ \/ ___| */
4/* \___ \ / _ \ | |_ | |_) | / _ \ | \| | | | | || |_| | | \___ \ */
5/* ___) / ___ \| _| | _ < / ___ \| |\ | | | |__ _| |_| |___) | */
6/* |____/_/ \_|_| |_| \_/_/ \_|_| \_| |_| |_| |____/|____/ */
7/* */
14/* ************************************************************************** */
15
17#include "o2s/log.h"
18
19#include <fcntl.h> // open
20
21#include <errno.h>
22#include <stdbool.h>
23#include <string.h> // strerror
24#include <unistd.h> // close
25
26#ifndef FILE_STREAM_BUFFER_SIZE
28# define FILE_STREAM_BUFFER_SIZE 4096
29#endif
30
35ifstream_t file_open(const char* file_name, int flags)
36{
37 int descriptor = open(file_name, flags);
38
39 if (descriptor < 0)
40 {
41 log_error("Unable to open \"%s\": %s", file_name, strerror(errno));
42 return (ifstream_t){.descriptor = -1, .opened = false};
43 }
44 ifstream_t file = file_from_descriptor(descriptor);
45 file.stream.accumulate = (bool(*)(istream_t*, size_t))file_accumulate;
46 if (file.descriptor == descriptor)
47 file.opened = true;
48 else
49 close(descriptor);
50 return file;
51}
52
55{
56 ifstream_t file = {.descriptor = descriptor, .opened = false};
57
59 if (file.stream.buffer.capacity == 0)
60 {
61 log_error("malloc failed: %s", strerror(errno));
62 file.descriptor = -1;
63 }
64 return file;
65}
#define FILE_STREAM_BUFFER_SIZE
Definition open.c:28
ifstream_t file_from_descriptor(int descriptor)
Construct a file input stream from an externally managed file descriptor.
Definition open.c:54
ifstream_t file_open(const char *file_name, int flags)
Construct a file input stream : Open the file and allocate the buffer.
Definition open.c:35
Buffered file reader.
#define InputStreamInit(Size, Accumulate)
Convenient wrapper around istream_init that casts Accumulate.
Simplistic logging utilities.
#define log_error(...)
Report a condition causing the current operation to abort.
Definition log.h:83
bool file_accumulate_infinite(ifstream_t *file, size_t count)
If possible, accumulate count bytes before returning.
Definition read.c:69
bool file_accumulate(ifstream_t *file, size_t count)
If possible, accumulate count bytes before returning.
Definition read.c:87
Dynamic string implementation.
size_t capacity
Maximum number of elements that can be stored.
Definition deque.h:32
File Input Stream.
bool opened
Is this file still open ?
int descriptor
Underlying file.
istream_t stream
Inherit from input stream.
Input Stream.
bool(* accumulate)(struct input_stream *self, size_t count)
Ask if the stream can provide at least count bytes to read.
queue_t buffer
Circular buffer of bytes.