src.ctf.fs: move ctf_fs_file to file.hpp
[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 struct ctf_fs_file *ctf_fs_file_create(const bt2c::Logger& parentLogger)
39 {
40 ctf_fs_file *file = new ctf_fs_file {parentLogger};
41 file->path = g_string_new(NULL);
42 if (!file->path) {
43 goto error;
44 }
45
46 goto end;
47
48 error:
49 ctf_fs_file_destroy(file);
50 file = NULL;
51
52 end:
53 return file;
54 }
55
56 int ctf_fs_file_open(struct ctf_fs_file *file, const char *mode)
57 {
58 int ret = 0;
59 struct stat stat;
60
61 BT_CPPLOGI_SPEC(file->logger, "Opening file \"{}\" with mode \"{}\"", file->path->str, mode);
62 file->fp = fopen(file->path->str, mode);
63 if (!file->fp) {
64 BT_CPPLOGE_ERRNO_APPEND_CAUSE_SPEC(file->logger, "Cannot open file", ": path={}, mode={}",
65 file->path->str, mode);
66 goto error;
67 }
68
69 BT_CPPLOGI_SPEC(file->logger, "Opened file: {}", fmt::ptr(file->fp));
70
71 if (fstat(fileno(file->fp), &stat)) {
72 BT_CPPLOGE_ERRNO_APPEND_CAUSE_SPEC(file->logger, "Cannot get file information", ": path={}",
73 file->path->str);
74 goto error;
75 }
76
77 file->size = stat.st_size;
78 BT_CPPLOGI_SPEC(file->logger, "File is {} bytes", (intmax_t) file->size);
79 goto end;
80
81 error:
82 ret = -1;
83
84 if (file->fp) {
85 if (fclose(file->fp)) {
86 BT_CPPLOGE_SPEC(file->logger, "Cannot close file \"{}\": {}", file->path->str,
87 strerror(errno));
88 }
89 }
90
91 end:
92 return ret;
93 }
This page took 0.039901 seconds and 4 git commands to generate.