[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 |
|
---|
| 9 | using namespace nv;
|
---|
| 10 |
|
---|
| 11 | c_stream::c_stream()
|
---|
| 12 | : m_file( nullptr )
|
---|
| 13 | , m_file_name( "" )
|
---|
| 14 | , m_file_size( size_t(-1) )
|
---|
| 15 | {
|
---|
| 16 |
|
---|
| 17 | }
|
---|
| 18 |
|
---|
| 19 | c_stream::c_stream( void* pfile, const char* filename )
|
---|
[125] | 20 | : m_file( pfile )
|
---|
[124] | 21 | , m_file_name( filename )
|
---|
| 22 | , m_file_size( size_t(-1) )
|
---|
| 23 | {
|
---|
| 24 |
|
---|
| 25 | }
|
---|
| 26 |
|
---|
| 27 | c_stream::~c_stream()
|
---|
| 28 | {
|
---|
| 29 | if ( m_file )
|
---|
| 30 | {
|
---|
| 31 | ::fclose( (FILE*)m_file );
|
---|
| 32 | }
|
---|
| 33 | }
|
---|
| 34 |
|
---|
| 35 | size_t c_stream::read( void* buffer, size_t size, size_t count )
|
---|
| 36 | {
|
---|
| 37 | NV_ASSERT( buffer != nullptr && size != 0 && count != 0, "Bad parameter passed to read!" );
|
---|
| 38 | return m_file ? ::fread( buffer, size, count, (FILE*)m_file ) : 0;
|
---|
| 39 | }
|
---|
| 40 |
|
---|
[279] | 41 | size_t c_stream::write( const void* buffer, size_t size, size_t count )
|
---|
[124] | 42 | {
|
---|
| 43 | NV_ASSERT( buffer != nullptr && size != 0 && count != 0, "Bad parameter passed to write!" );
|
---|
| 44 | return m_file ? ::fwrite( buffer, size, count, (FILE*)m_file ) : 0;
|
---|
| 45 | }
|
---|
| 46 |
|
---|
[198] | 47 | bool c_stream::seek( long offset, origin orig )
|
---|
[124] | 48 | {
|
---|
| 49 | return m_file != nullptr && ( ::fseek( (FILE*)m_file, (long)offset, static_cast<int>(orig) ) == 0 );
|
---|
| 50 | }
|
---|
| 51 |
|
---|
| 52 | size_t c_stream::tell()
|
---|
| 53 | {
|
---|
[198] | 54 | return m_file != nullptr ? static_cast< size_t >( ::ftell( (FILE*)m_file ) ) : 0;
|
---|
[124] | 55 | }
|
---|
| 56 |
|
---|
| 57 | size_t c_stream::size()
|
---|
| 58 | {
|
---|
[125] | 59 | if ( m_file == nullptr || m_file_name == nullptr )
|
---|
[124] | 60 | {
|
---|
| 61 | return 0;
|
---|
| 62 | }
|
---|
| 63 |
|
---|
| 64 | if ( m_file_size == size_t(-1) )
|
---|
| 65 | {
|
---|
| 66 | struct stat fstat;
|
---|
[125] | 67 | int result = stat(m_file_name, &fstat );
|
---|
[124] | 68 | if ( result != 0 )
|
---|
| 69 | {
|
---|
| 70 | return 0;
|
---|
| 71 | }
|
---|
| 72 | m_file_size = (size_t) (fstat.st_size);
|
---|
| 73 | }
|
---|
| 74 |
|
---|
| 75 | return m_file_size;
|
---|
| 76 | }
|
---|
| 77 |
|
---|
| 78 | void c_stream::flush()
|
---|
| 79 | {
|
---|
| 80 | if ( m_file != nullptr )
|
---|
| 81 | {
|
---|
| 82 | ::fflush( (FILE*)m_file );
|
---|
| 83 | }
|
---|
| 84 | }
|
---|