ctf: use `bt2c::Logger` throughout `src.ctf.fs`, `src.ctf.lttng-live`
[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
0f5c5d5c 11#include "cpp-common/vendor/fmt/format.h"
98903a3e 12
087cd0f5 13#include "file.hpp"
c7e1be4b 14#include "fs.hpp"
e98a2d6e
PP
15
16void ctf_fs_file_destroy(struct ctf_fs_file *file)
17{
4164020e
SM
18 if (!file) {
19 return;
20 }
21
22 if (file->fp) {
0f5c5d5c
SM
23 BT_CPPLOGD_SPEC(file->logger, "Closing file \"{}\" ({})",
24 file->path ? file->path->str : NULL, fmt::ptr(file->fp));
4164020e
SM
25
26 if (fclose(file->fp)) {
0f5c5d5c
SM
27 BT_CPPLOGE_SPEC(file->logger, "Cannot close file \"{}\": {}",
28 file->path ? file->path->str : "NULL", strerror(errno));
4164020e
SM
29 }
30 }
31
32 if (file->path) {
33 g_string_free(file->path, TRUE);
34 }
35
afb0f12b 36 delete file;
e98a2d6e
PP
37}
38
0f5c5d5c 39struct ctf_fs_file *ctf_fs_file_create(const bt2c::Logger& parentLogger)
e98a2d6e 40{
0f5c5d5c 41 ctf_fs_file *file = new ctf_fs_file {parentLogger};
4164020e
SM
42 file->path = g_string_new(NULL);
43 if (!file->path) {
44 goto error;
45 }
e98a2d6e 46
4164020e 47 goto end;
e98a2d6e
PP
48
49error:
4164020e
SM
50 ctf_fs_file_destroy(file);
51 file = NULL;
e98a2d6e
PP
52
53end:
4164020e 54 return file;
e98a2d6e
PP
55}
56
55314f2a 57int ctf_fs_file_open(struct ctf_fs_file *file, const char *mode)
e98a2d6e 58{
4164020e
SM
59 int ret = 0;
60 struct stat stat;
61
0f5c5d5c 62 BT_CPPLOGI_SPEC(file->logger, "Opening file \"{}\" with mode \"{}\"", file->path->str, mode);
4164020e
SM
63 file->fp = fopen(file->path->str, mode);
64 if (!file->fp) {
0f5c5d5c
SM
65 BT_CPPLOGE_ERRNO_APPEND_CAUSE_SPEC(file->logger, "Cannot open file", ": path={}, mode={}",
66 file->path->str, mode);
4164020e
SM
67 goto error;
68 }
69
0f5c5d5c 70 BT_CPPLOGI_SPEC(file->logger, "Opened file: {}", fmt::ptr(file->fp));
4164020e
SM
71
72 if (fstat(fileno(file->fp), &stat)) {
0f5c5d5c
SM
73 BT_CPPLOGE_ERRNO_APPEND_CAUSE_SPEC(file->logger, "Cannot get file information", ": path={}",
74 file->path->str);
4164020e
SM
75 goto error;
76 }
77
78 file->size = stat.st_size;
0f5c5d5c 79 BT_CPPLOGI_SPEC(file->logger, "File is {} bytes", (intmax_t) file->size);
4164020e 80 goto end;
e98a2d6e
PP
81
82error:
4164020e 83 ret = -1;
e98a2d6e 84
4164020e
SM
85 if (file->fp) {
86 if (fclose(file->fp)) {
0f5c5d5c
SM
87 BT_CPPLOGE_SPEC(file->logger, "Cannot close file \"{}\": {}", file->path->str,
88 strerror(errno));
4164020e
SM
89 }
90 }
e98a2d6e
PP
91
92end:
4164020e 93 return ret;
e98a2d6e 94}
This page took 0.127273 seconds and 4 git commands to generate.