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