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