compat: fix compilation with !BABELTRACE_HAVE_OPEN_MEMSTREAM
[babeltrace.git] / src / plugins / ctf / fs-src / file.c
CommitLineData
e98a2d6e 1/*
0235b0db 2 * SPDX-License-Identifier: MIT
e98a2d6e 3 *
0235b0db 4 * Copyright 2016 Philippe Proulx <pproulx@efficios.com>
e98a2d6e
PP
5 */
6
4c65a157 7#define BT_COMP_LOG_SELF_COMP (file->self_comp)
98903a3e
PP
8#define BT_LOG_OUTPUT_LEVEL (file->log_level)
9#define BT_LOG_TAG "PLUGIN/SRC.CTF.FS/FILE"
d9c39b0a 10#include "logging/comp-logging.h"
98903a3e 11
e98a2d6e
PP
12#include <stdio.h>
13#include <sys/types.h>
14#include <sys/stat.h>
15#include <unistd.h>
16#include <glib.h>
56a1cced 17#include "file.h"
e98a2d6e 18
e7a4393b 19BT_HIDDEN
e98a2d6e
PP
20void ctf_fs_file_destroy(struct ctf_fs_file *file)
21{
e98a2d6e
PP
22 if (!file) {
23 return;
24 }
25
26 if (file->fp) {
4c65a157 27 BT_COMP_LOGD("Closing file \"%s\" (%p)",
dcbaa1ca 28 file->path ? file->path->str : NULL, file->fp);
e98a2d6e
PP
29
30 if (fclose(file->fp)) {
4c65a157 31 BT_COMP_LOGE("Cannot close file \"%s\": %s",
dcbaa1ca
JG
32 file->path ? file->path->str : "NULL",
33 strerror(errno));
e98a2d6e
PP
34 }
35 }
36
37 if (file->path) {
38 g_string_free(file->path, TRUE);
39 }
40
41 g_free(file);
42}
43
e7a4393b 44BT_HIDDEN
4c65a157
PP
45struct ctf_fs_file *ctf_fs_file_create(bt_logging_level log_level,
46 bt_self_component *self_comp)
e98a2d6e
PP
47{
48 struct ctf_fs_file *file = g_new0(struct ctf_fs_file, 1);
49
50 if (!file) {
51 goto error;
52 }
53
98903a3e 54 file->log_level = log_level;
4c65a157 55 file->self_comp = self_comp;
e98a2d6e
PP
56 file->path = g_string_new(NULL);
57 if (!file->path) {
58 goto error;
59 }
60
61 goto end;
62
63error:
64 ctf_fs_file_destroy(file);
65 file = NULL;
66
67end:
68 return file;
69}
70
e7a4393b 71BT_HIDDEN
55314f2a 72int ctf_fs_file_open(struct ctf_fs_file *file, const char *mode)
e98a2d6e
PP
73{
74 int ret = 0;
75 struct stat stat;
76
4c65a157 77 BT_COMP_LOGI("Opening file \"%s\" with mode \"%s\"", file->path->str, mode);
e98a2d6e
PP
78 file->fp = fopen(file->path->str, mode);
79 if (!file->fp) {
b30284d1
SM
80 BT_COMP_LOGE_APPEND_CAUSE_ERRNO(file->self_comp,
81 "Cannot open file", ": path=%s, mode=%s",
82 file->path->str, mode);
e98a2d6e
PP
83 goto error;
84 }
85
4c65a157 86 BT_COMP_LOGI("Opened file: %p", file->fp);
e98a2d6e
PP
87
88 if (fstat(fileno(file->fp), &stat)) {
b30284d1
SM
89 BT_COMP_LOGE_APPEND_CAUSE_ERRNO(file->self_comp,
90 "Cannot get file information",
91 ": path=%s", file->path->str);
e98a2d6e
PP
92 goto error;
93 }
94
95 file->size = stat.st_size;
4c65a157 96 BT_COMP_LOGI("File is %jd bytes", (intmax_t) file->size);
e98a2d6e
PP
97 goto end;
98
99error:
100 ret = -1;
101
102 if (file->fp) {
103 if (fclose(file->fp)) {
4c65a157 104 BT_COMP_LOGE("Cannot close file \"%s\": %s", file->path->str,
e98a2d6e
PP
105 strerror(errno));
106 }
107 }
108
109end:
110 return ret;
111}
This page took 0.082617 seconds and 4 git commands to generate.