1 // sg_file.cxx -- File I/O routines
3 // Written by Curtis Olson, started November 1999.
5 // Copyright (C) 1999 Curtis L. Olson - curt@flightgear.org
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>
32 #include <simgear/debug/logstream.hxx>
34 #include "sg_file.hxx"
39 SGFile::SGFile( const string &file) {
40 set_type( sgFileType );
49 // open the file based on specified direction
50 bool SGFile::open( SGProtocolDir dir ) {
51 if ( dir == SG_IO_OUT ) {
53 fp = _open( file_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC,
56 fp = std::open( file_name.c_str(), O_WRONLY | O_CREAT | O_TRUNC,
57 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |
60 } else if ( dir == SG_IO_IN ) {
62 fp = _open( file_name.c_str(), O_RDONLY );
64 fp = std::open( file_name.c_str(), O_RDONLY );
67 FG_LOG( FG_IO, FG_ALERT,
68 "Error: bidirection mode not available for files." );
73 FG_LOG( FG_IO, FG_ALERT, "Error opening file: " << file_name );
81 // read a block of data of specified size
82 int SGFile::read( char *buf, int length ) {
85 int result = _read( fp, buf, length );
87 int result = std::read( fp, buf, length );
94 // read a line of data, length is max size of input buffer
95 int SGFile::readline( char *buf, int length ) {
96 // save our current position
97 int pos = lseek( fp, 0, SEEK_CUR );
101 int result = _read( fp, buf, length );
103 int result = std::read( fp, buf, length );
106 // find the end of line and reset position
108 for ( i = 0; i < result && buf[i] != '\n'; ++i );
109 if ( buf[i] == '\n' ) {
114 lseek( fp, pos + result, SEEK_SET );
117 buf[ result ] = '\0';
123 // write data to a file
124 int SGFile::write( char *buf, int length ) {
126 int result = _write( fp, buf, length );
128 int result = std::write( fp, buf, length );
130 if ( result != length ) {
131 FG_LOG( FG_IO, FG_ALERT, "Error writing data: " << file_name );
138 // write null terminated string to a file
139 int SGFile::writestring( char *str ) {
140 int length = strlen( str );
141 return write( str, length );
146 bool SGFile::close() {
148 if ( _close( fp ) == -1 ) {
150 if ( std::close( fp ) == -1 ) {