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