RESTinio

sendfile_defs_default.hpp
Go to the documentation of this file.
1/*
2 restinio
3*/
4
11#pragma once
12
13#include <cstdio>
14
15 namespace restinio
16{
17
21 using file_descriptor_t = std::FILE*;
22 using file_offset_t = std::int64_t;
23 using file_size_t = std::uint64_t;
25
26
34
36 constexpr file_descriptor_t null_file_descriptor(){ return nullptr; }
37
39 inline file_descriptor_t
40 open_file( const char * file_path )
41{
42 file_descriptor_t file_descriptor = std::fopen( file_path, "rb" );
43
44 if( null_file_descriptor() == file_descriptor )
45 {
46 throw exception_t{ fmt::format( "std::fopen failed: '{}'", file_path ) };
47 }
48
49 return file_descriptor;
50}
51
53 template < typename META >
54META
55 get_file_meta( file_descriptor_t fd )
56{
57 file_size_t fsize = 0;
58
59 if( null_file_descriptor() != fd )
60 {
61 // Obtain file size:
62 if( 0 == std::fseek( fd , 0 , SEEK_END ) )
63 {
64 const auto end_pos = std::ftell( fd );
65
66 if( -1 != end_pos )
67 {
68 fsize = static_cast< file_size_t >( end_pos );
69 std::rewind( fd );
70 }
71 else
72 {
73 throw exception_t{ "std::ftell failed" };
74 }
75 }
76 else
77 {
78 throw exception_t{ "std::fseek failed" };
79 }
80 }
81
82 // No way to get last modification,
83 // Use current time instead.
84 return META{ fsize, std::chrono::system_clock::now() };
85}
86
88 inline void
89 close_file( file_descriptor_t fd )
90{
91 std::fclose( fd );
92}
94
95} /* namespace restinio */
restinio::exception_t
Exception class for all exceptions thrown by RESTinio.
Definition: exception.hpp:26
restinio
Definition: asio_include.hpp:21
restinio::null_file_descriptor
constexpr file_descriptor_t null_file_descriptor()
Get file descriptor which stands for null.
Definition: sendfile_defs_default.hpp:36
restinio::file_size_t
std::uint64_t file_size_t
Definition: sendfile_defs_default.hpp:23
restinio::close_file
void close_file(file_descriptor_t fd)
Close file by its descriptor.
Definition: sendfile_defs_default.hpp:89
restinio::file_offset_t
std::int64_t file_offset_t
Definition: sendfile_defs_default.hpp:22
restinio::file_descriptor_t
std::FILE * file_descriptor_t
Definition: sendfile_defs_default.hpp:21
restinio::open_file
file_descriptor_t open_file(const char *file_path)
Open file.
Definition: sendfile_defs_default.hpp:40
restinio::get_file_meta
META get_file_meta(file_descriptor_t fd)
Get file size.
Definition: sendfile_defs_default.hpp:55
SEEK_END
#define SEEK_END
Definition: zconf.h:500