File: file.cpp

package info (click to toggle)
dnf5 5.4.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 17,960 kB
  • sloc: cpp: 94,312; python: 3,370; xml: 1,073; ruby: 600; sql: 250; ansic: 232; sh: 104; perl: 62; makefile: 30
file content (341 lines) | stat: -rw-r--r-- 8,442 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Copyright Contributors to the DNF5 project.
// Copyright Contributors to the libdnf project.
// SPDX-License-Identifier: LGPL-2.1-or-later
//
// This file is part of libdnf: https://github.com/rpm-software-management/libdnf/
//
// Libdnf is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or
// (at your option) any later version.
//
// Libdnf is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with libdnf.  If not, see <https://www.gnu.org/licenses/>.


#include "libdnf5/utils/fs/file.hpp"

#include "libdnf5/common/exception.hpp"
#include "libdnf5/utils/bgettext/bgettext-lib.h"
#include "libdnf5/utils/bgettext/bgettext-mark-domain.h"

extern "C" {
#include <solv/solv_xfopen.h>
}

#include <stdio.h>

#include <algorithm>

#define libdnf_assert_file_open() libdnf_assert(file != nullptr, "The operation requires an open file");


namespace libdnf5::utils::fs {

File::File() = default;


File::File(const std::filesystem::path & path, const char * mode, bool use_solv_xfopen) {
    open(path, mode, use_solv_xfopen);
}


File::File(int fd, const std::filesystem::path & path, const char * mode, bool use_solv_xfopen_fd) {
    open(fd, path, mode, use_solv_xfopen_fd);
}


File::File(File && f) noexcept : path(std::move(f.path)), file(f.file) {
    f.file = nullptr;
}


File & File::operator=(File && f) {
    if (&f != this) {
        close();
        path = std::move(f.path);
        file = f.file;
        f.file = nullptr;
    }

    return *this;
}


File::~File() {
    try {
        close();
    } catch (std::exception &) {
        // TODO(lukash) consider logging or printing the exception
    }
}


void File::open(const std::filesystem::path & path, const char * mode, bool use_solv_xfopen) {
    close();

    file = use_solv_xfopen ? solv_xfopen(path.c_str(), mode) : std::fopen(path.c_str(), mode);

    if (file == nullptr) {
        this->path = "";
        throw FileSystemError(errno, path, M_("cannot open file"));
    }

    this->path = path;
}


void File::open(int fd, const std::filesystem::path & path, const char * mode, bool use_solv_xfopen_fd) {
    close();

    file = use_solv_xfopen_fd ? solv_xfopen_fd(path.c_str(), fd, mode) : ::fdopen(fd, mode);
    if (file == nullptr) {
        this->path = "";
        throw FileSystemError(errno, path, M_("cannot open file from fd"));
    }

    this->path = path;
}


void File::close() {
    if (file != nullptr) {
        if (std::fclose(file) != 0) {
            throw FileSystemError(errno, path, M_("cannot close file"));
        }
    }

    file = nullptr;
    path.clear();
}


std::FILE * File::release() noexcept {
    auto * p = file;
    file = nullptr;
    path.clear();
    return p;
}


std::size_t File::read(void * buffer, std::size_t count) {
    libdnf_assert_file_open();

    auto res = std::fread(buffer, sizeof(char), count, file);

    if (res != count) {
        if (std::feof(file) != 0) {
            return res;
        }

        libdnf_assert(
            std::ferror(file) != 0, "Failed to read \"{}\", error expected but no error detected", path.native());

        throw FileSystemError(errno, path, M_("error reading file"));
    }

    return res;
}


void File::write(const void * buffer, std::size_t count) {
    libdnf_assert_file_open();

    if (std::fwrite(buffer, sizeof(char), count, file) != count) {
        libdnf_assert(std::feof(file) == 0, "EOF reached while writing file \"{}\"", path.native());
        libdnf_assert(
            std::ferror(file) > 0, "Failed to write \"{}\", error expected but no error detected", path.native());

        throw FileSystemError(errno, path, M_("error writing file"));
    }
}


bool File::getc(char & c) {
    libdnf_assert_file_open();

    int res;
    if ((res = std::fgetc(file)) == EOF) {
        if (is_at_eof()) {
            return false;
        }

        throw FileSystemError(errno, path, M_("error reading file"));
    }

    c = static_cast<char>(res);
    return true;
}


void File::putc(char c) {
    libdnf_assert_file_open();

    if (std::fputc(c, file) == EOF) {
        throw FileSystemError(errno, path, M_("error writing file"));
    }
}


void File::flush() {
    libdnf_assert_file_open();

    if (std::fflush(file) == -1) {
        throw FileSystemError(errno, path, M_("error flushing file"));
    }
}


void File::seek(long offset, int whence) {
    libdnf_assert_file_open();

    if (std::fseek(file, offset, whence) == -1) {
        throw FileSystemError(errno, path, M_("error seeking in file"));
    }
}


long File::tell() const {
    libdnf_assert_file_open();

    auto res = std::ftell(file);

    if (res == -1) {
        throw FileSystemError(errno, path, M_("error retrieving file position"));
    }

    return res;
}


void File::rewind() {
    libdnf_assert_file_open();
    std::rewind(file);
}


bool File::is_at_eof() const {
    libdnf_assert_file_open();
    return std::feof(file);
}


std::string File::read(std::size_t count) {
    libdnf_assert_file_open();

    // Try to detect the length to the end of the file.
    std::size_t length_to_end;
    bool length_detected{false};
    if (auto cur_pos = std::ftell(file); cur_pos != -1) {
        if (std::fseek(file, 0, SEEK_END) != -1) {
            if (auto end_pos = std::ftell(file); end_pos != -1) {
                length_to_end = static_cast<std::size_t>(end_pos - cur_pos);
                length_detected = true;
            }
        }
        std::fseek(file, cur_pos, SEEK_SET);
    }

    std::string res;

    if (length_detected) {
        // The file length is known. Allocate memory at once and read data.
        std::size_t to_read = count == 0 ? length_to_end : std::min(length_to_end, count);
        res.resize(to_read);
        std::size_t size = read(res.data(), to_read);
        libdnf_assert(size == to_read, "Short read occurred: expected to read {}, have read {}.", to_read, size);
    } else {
        // Could not determine file length. A fallback solution, we read data in blocks and reallocate memory.
        char buffer[4096];
        if (count > 0) {
            // We read at most `count` characters.
            do {
                std::size_t to_read = std::min(sizeof buffer, count);
                auto chars_read = read(buffer, to_read);
                res.append(buffer, chars_read);
                if (chars_read < to_read) {
                    break;
                }
                count -= chars_read;
            } while (count > 0);
        } else {
            // We are reading the file to the end.
            do {
                auto chars_read = read(buffer, sizeof buffer);
                res.append(buffer, chars_read);
                if (chars_read < sizeof buffer) {
                    break;
                }
            } while (true);
        }
    }

    return res;
}


bool File::read_line(std::string & line) {
    libdnf_assert_file_open();

    char * buf = nullptr;
    std::size_t buf_len = 0;
    ssize_t line_len = 0;
    if ((line_len = getline(&buf, &buf_len, file)) == -1) {
        if (errno != ENOMEM) {
            free(buf);
        }

        if (is_at_eof()) {
            return false;
        }

        throw FileSystemError(errno, path, M_("error reading a line from file"));
    }

    while (line_len > 0 && (buf[line_len - 1] == '\r' || buf[line_len - 1] == '\n')) {
        --line_len;
    }
    line.assign(buf, static_cast<std::size_t>(line_len));
    free(buf);
    return true;
}


void File::write(std::string_view data) {
    write(data.data(), data.size());
}


File::operator bool() const noexcept {
    return file != nullptr;
}


const std::filesystem::path & File::get_path() const noexcept {
    return path;
}


std::FILE * File::get() const noexcept {
    return file;
}


int File::get_fd() const {
    libdnf_assert_file_open();

    int fd = ::fileno(file);

    if (fd == -1) {
        throw FileSystemError(errno, path, M_("error retrieving file descriptor"));
    }

    return fd;
}

}  // namespace libdnf5::utils::fs