1 | // Copyright (C) 2012-2015 ChaosForge Ltd
|
---|
2 | // http://chaosforge.org/
|
---|
3 | //
|
---|
4 | // This file is part of Nova libraries.
|
---|
5 | // For conditions of distribution and use, see copying.txt file in root folder.
|
---|
6 |
|
---|
7 | #include "nv/io/c_stream.hh"
|
---|
8 | #include <cstdio>
|
---|
9 | #include <sys/stat.h>
|
---|
10 |
|
---|
11 | using namespace nv;
|
---|
12 |
|
---|
13 | c_stream::c_stream()
|
---|
14 | : m_file( nullptr )
|
---|
15 | , m_file_name( "" )
|
---|
16 | , m_file_size( size_t(-1) )
|
---|
17 | {
|
---|
18 |
|
---|
19 | }
|
---|
20 |
|
---|
21 | c_stream::c_stream( void* pfile, const char* filename )
|
---|
22 | : m_file( pfile )
|
---|
23 | , m_file_name( filename )
|
---|
24 | , m_file_size( size_t(-1) )
|
---|
25 | {
|
---|
26 |
|
---|
27 | }
|
---|
28 |
|
---|
29 | c_stream::~c_stream()
|
---|
30 | {
|
---|
31 | if ( m_file )
|
---|
32 | {
|
---|
33 | ::fclose( reinterpret_cast<FILE*>( m_file ) );
|
---|
34 | }
|
---|
35 | }
|
---|
36 |
|
---|
37 | nv::size_t c_stream::read( void* buffer, nv::size_t size, nv::size_t count )
|
---|
38 | {
|
---|
39 | NV_ASSERT( buffer != nullptr && size != 0 && count != 0, "Bad parameter passed to read!" );
|
---|
40 | return m_file ? ::fread( buffer, size, count, reinterpret_cast<FILE*>( m_file ) ) : 0;
|
---|
41 | }
|
---|
42 |
|
---|
43 | nv::size_t c_stream::write( const void* buffer, nv::size_t size, nv::size_t count )
|
---|
44 | {
|
---|
45 | NV_ASSERT( buffer != nullptr && size != 0 && count != 0, "Bad parameter passed to write!" );
|
---|
46 | return m_file ? ::fwrite( buffer, size, count, reinterpret_cast<FILE*>( m_file ) ) : 0;
|
---|
47 | }
|
---|
48 |
|
---|
49 | bool c_stream::seek( long offset, origin orig )
|
---|
50 | {
|
---|
51 | return m_file != nullptr && ( ::fseek( reinterpret_cast<FILE*>( m_file ), offset, static_cast<int>(orig) ) == 0 );
|
---|
52 | }
|
---|
53 |
|
---|
54 | nv::size_t c_stream::tell()
|
---|
55 | {
|
---|
56 | return m_file != nullptr ? static_cast< nv::size_t >( ::ftell( reinterpret_cast<FILE*>( m_file ) ) ) : 0;
|
---|
57 | }
|
---|
58 |
|
---|
59 | nv::size_t c_stream::size()
|
---|
60 | {
|
---|
61 | if ( m_file == nullptr || m_file_name == nullptr )
|
---|
62 | {
|
---|
63 | return 0;
|
---|
64 | }
|
---|
65 |
|
---|
66 | if ( m_file_size == size_t(-1) )
|
---|
67 | {
|
---|
68 | struct stat fstat;
|
---|
69 | int result = stat(m_file_name, &fstat );
|
---|
70 | if ( result != 0 )
|
---|
71 | {
|
---|
72 | return 0;
|
---|
73 | }
|
---|
74 | m_file_size = static_cast<size_t>(fstat.st_size);
|
---|
75 | }
|
---|
76 |
|
---|
77 | return m_file_size;
|
---|
78 | }
|
---|
79 |
|
---|
80 | void c_stream::flush()
|
---|
81 | {
|
---|
82 | if ( m_file != nullptr )
|
---|
83 | {
|
---|
84 | ::fflush( reinterpret_cast<FILE*>( m_file ) );
|
---|
85 | }
|
---|
86 | }
|
---|