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
15namespace restinio
16{
17
21using file_descriptor_t = std::FILE*;
22using file_offset_t = std::int64_t;
23using file_size_t = std::uint64_t;
25
26
34
36constexpr file_descriptor_t null_file_descriptor(){ return nullptr; }
37
40open_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
53template < typename META >
54META
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
88inline void
90{
91 std::fclose( fd );
92}
94
95} /* namespace restinio */
Exception class for all exceptions thrown by RESTinio.
Definition: exception.hpp:26
constexpr file_descriptor_t null_file_descriptor()
Get file descriptor which stands for null.
std::uint64_t file_size_t
void close_file(file_descriptor_t fd)
Close file by its descriptor.
std::int64_t file_offset_t
std::FILE * file_descriptor_t
file_descriptor_t open_file(const char *file_path)
Open file.
META get_file_meta(file_descriptor_t fd)
Get file size.
#define SEEK_END
Definition: zconf.h:500