1 // sg_file.cxx -- File I/O routines
3 // Written by Curtis Olson, started November 1999.
5 // Copyright (C) 1999 Curtis L. Olson - http://www.flightgear.org/~curt
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 #include <simgear/compiler.h>
28 #if defined(_MSC_VER) || defined(__MINGW32__)
32 #include <simgear/debug/logstream.hxx>
34 #include "sg_file.hxx"
39 SGFile::SGFile( const string &file) {
40 set_type( sgFileType );
50 // open the file based on specified direction
51 bool SGFile::open( const SGProtocolDir d ) {
54 if ( get_dir() == SG_IO_OUT ) {
55 #if defined(_MSC_VER) || defined(__MINGW32__)
58 mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
60 fp = ::open( file_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC, mode );
61 } else if ( get_dir() == SG_IO_IN ) {
62 fp = ::open( file_name.c_str(), O_RDONLY );
64 SG_LOG( SG_IO, SG_ALERT,
65 "Error: bidirection mode not available for files." );
70 SG_LOG( SG_IO, SG_ALERT, "Error opening file: " << file_name );
79 // read a block of data of specified size
80 int SGFile::read( char *buf, int length ) {
82 ssize_t result = ::read( fp, buf, length );
83 if ( length > 0 && result == 0 ) {
90 // read a line of data, length is max size of input buffer
91 int SGFile::readline( char *buf, int length ) {
92 // save our current position
93 int pos = lseek( fp, 0, SEEK_CUR );
96 ssize_t result = ::read( fp, buf, length );
97 if ( length > 0 && result == 0 ) {
101 // find the end of line and reset position
103 for ( i = 0; i < result && buf[i] != '\n'; ++i );
104 if ( buf[i] == '\n' ) {
109 lseek( fp, pos + result, SEEK_SET );
112 buf[ result ] = '\0';
118 // write data to a file
119 int SGFile::write( const char *buf, const int length ) {
120 int result = ::write( fp, buf, length );
121 if ( result != length ) {
122 SG_LOG( SG_IO, SG_ALERT, "Error writing data: " << file_name );
129 // write null terminated string to a file
130 int SGFile::writestring( const char *str ) {
131 int length = strlen( str );
132 return write( str, length );
137 bool SGFile::close() {
138 if ( ::close( fp ) == -1 ) {