source: trunk/src/io/c_stream.cc @ 376

Last change on this file since 376 was 376, checked in by epyon, 10 years ago
  • stl/assert.hh, stl/capi.hh, size_t independent
  • GCC 4.8 compatibility
  • using template usage
  • various minor changes
File size: 1.8 KB
Line 
1// Copyright (C) 2012-2014 ChaosForge Ltd
2// This file is part of NV Libraries.
3// For conditions of distribution and use, see copyright notice in nv.hh
4
5#include "nv/io/c_stream.hh"
6#include <cstdio>
7#include <sys/stat.h>
8
9using namespace nv;
10
11c_stream::c_stream()
12        : m_file( nullptr )
13        , m_file_name( "" )
14        , m_file_size( size_t(-1) )
15{
16
17}
18
19c_stream::c_stream( void* pfile, const char* filename )
20        : m_file( pfile )
21        , m_file_name( filename )
22        , m_file_size( size_t(-1) )
23{
24
25}
26
27c_stream::~c_stream()
28{
29        if ( m_file )
30        {
31                ::fclose( (FILE*)m_file );
32        }
33}
34
35nv::size_t c_stream::read( void* buffer, nv::size_t size, nv::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
41nv::size_t c_stream::write( const void* buffer, nv::size_t size, nv::size_t count )
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
47bool c_stream::seek( long offset, origin orig )
48{
49        return m_file != nullptr && ( ::fseek( (FILE*)m_file, (long)offset, static_cast<int>(orig) ) == 0 );
50}
51
52nv::size_t c_stream::tell()
53{
54        return m_file != nullptr ? static_cast< nv::size_t >( ::ftell( (FILE*)m_file ) ) : 0;
55}
56
57nv::size_t c_stream::size()
58{
59        if ( m_file == nullptr || m_file_name == nullptr )
60        {
61                return 0;
62        }
63
64        if ( m_file_size == size_t(-1) )
65        {
66                struct stat fstat;
67                int result = stat(m_file_name, &fstat );
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
78void c_stream::flush()
79{
80        if ( m_file != nullptr )
81        {
82                ::fflush( (FILE*)m_file );
83        }
84}
Note: See TracBrowser for help on using the repository browser.