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