ctf: allocate some structures with new
[babeltrace.git] / src / plugins / ctf / fs-src / file.cpp
... / ...
CommitLineData
1/*
2 * SPDX-License-Identifier: MIT
3 *
4 * Copyright 2016 Philippe Proulx <pproulx@efficios.com>
5 */
6
7#include <glib.h>
8#include <stdio.h>
9#include <sys/stat.h>
10
11#define BT_COMP_LOG_SELF_COMP (file->self_comp)
12#define BT_LOG_OUTPUT_LEVEL (file->log_level)
13#define BT_LOG_TAG "PLUGIN/SRC.CTF.FS/FILE"
14#include "logging/comp-logging.h"
15
16#include "file.hpp"
17#include "fs.hpp"
18
19void ctf_fs_file_destroy(struct ctf_fs_file *file)
20{
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
38 delete file;
39}
40
41struct ctf_fs_file *ctf_fs_file_create(bt_logging_level log_level, bt_self_component *self_comp)
42{
43 ctf_fs_file *file = new ctf_fs_file;
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 }
50
51 goto end;
52
53error:
54 ctf_fs_file_destroy(file);
55 file = NULL;
56
57end:
58 return file;
59}
60
61int ctf_fs_file_open(struct ctf_fs_file *file, const char *mode)
62{
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;
85
86error:
87 ret = -1;
88
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 }
94
95end:
96 return ret;
97}
This page took 0.022849 seconds and 4 git commands to generate.