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