src.ctf.fs: make ctf_fs_file_create return a unique_ptr
[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"
e98a2d6e
PP
14
15void ctf_fs_file_destroy(struct ctf_fs_file *file)
16{
4164020e
SM
17 if (!file) {
18 return;
19 }
20
21 if (file->fp) {
0f5c5d5c
SM
22 BT_CPPLOGD_SPEC(file->logger, "Closing file \"{}\" ({})",
23 file->path ? file->path->str : NULL, fmt::ptr(file->fp));
4164020e
SM
24
25 if (fclose(file->fp)) {
0f5c5d5c
SM
26 BT_CPPLOGE_SPEC(file->logger, "Cannot close file \"{}\": {}",
27 file->path ? file->path->str : "NULL", strerror(errno));
4164020e
SM
28 }
29 }
30
31 if (file->path) {
32 g_string_free(file->path, TRUE);
33 }
34
afb0f12b 35 delete file;
e98a2d6e
PP
36}
37
5ff12b25 38void ctf_fs_file_deleter::operator()(ctf_fs_file * const file) noexcept
e98a2d6e 39{
5ff12b25
SM
40 ctf_fs_file_destroy(file);
41}
42
43ctf_fs_file::UP ctf_fs_file_create(const bt2c::Logger& parentLogger)
44{
45 ctf_fs_file::UP file {new ctf_fs_file {parentLogger}};
46
4164020e
SM
47 file->path = g_string_new(NULL);
48 if (!file->path) {
49 goto error;
50 }
e98a2d6e 51
4164020e 52 goto end;
e98a2d6e
PP
53
54error:
5ff12b25 55 file.reset();
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
0f5c5d5c 66 BT_CPPLOGI_SPEC(file->logger, "Opening file \"{}\" with mode \"{}\"", file->path->str, mode);
4164020e
SM
67 file->fp = fopen(file->path->str, mode);
68 if (!file->fp) {
0f5c5d5c
SM
69 BT_CPPLOGE_ERRNO_APPEND_CAUSE_SPEC(file->logger, "Cannot open file", ": path={}, mode={}",
70 file->path->str, mode);
4164020e
SM
71 goto error;
72 }
73
0f5c5d5c 74 BT_CPPLOGI_SPEC(file->logger, "Opened file: {}", fmt::ptr(file->fp));
4164020e
SM
75
76 if (fstat(fileno(file->fp), &stat)) {
0f5c5d5c
SM
77 BT_CPPLOGE_ERRNO_APPEND_CAUSE_SPEC(file->logger, "Cannot get file information", ": path={}",
78 file->path->str);
4164020e
SM
79 goto error;
80 }
81
82 file->size = stat.st_size;
0f5c5d5c 83 BT_CPPLOGI_SPEC(file->logger, "File is {} bytes", (intmax_t) file->size);
4164020e 84 goto end;
e98a2d6e
PP
85
86error:
4164020e 87 ret = -1;
e98a2d6e 88
4164020e
SM
89 if (file->fp) {
90 if (fclose(file->fp)) {
0f5c5d5c
SM
91 BT_CPPLOGE_SPEC(file->logger, "Cannot close file \"{}\": {}", file->path->str,
92 strerror(errno));
4164020e
SM
93 }
94 }
e98a2d6e
PP
95
96end:
4164020e 97 return ret;
e98a2d6e 98}
This page took 0.09688 seconds and 4 git commands to generate.