input_stream.cpp

Go to the documentation of this file.
00001 /* $Id: input_stream.cpp 26456 2008-05-08 12:02:24Z suokko $ */
00002 /*
00003    Copyright (C) 2003 - 2008 by David White <dave@whitevine.net>
00004    Part of the Battle for Wesnoth Project http://www.wesnoth.org/
00005 
00006    This program is free software; you can redistribute it and/or modify
00007    it under the terms of the GNU General Public License version 2
00008    or at your option any later version.
00009    This program is distributed in the hope that it will be useful,
00010    but WITHOUT ANY WARRANTY.
00011 
00012    See the COPYING file for more details.
00013 */
00014 
00015 #include "../global.hpp"
00016 
00017 #include "input_stream.hpp"
00018 
00019 #ifndef _WIN32
00020 
00021 #include <algorithm>
00022 #include <iostream>
00023 #include <fcntl.h>
00024 #include <sys/types.h>
00025 #include <sys/stat.h>
00026 #include <unistd.h>
00027 
00028 #endif
00029 
00030 input_stream::input_stream(const std::string& path) : fd_(-1), path_(path)
00031 {
00032 #ifndef _WIN32
00033     if(path == "") {
00034         return;
00035     }
00036 
00037     const int res = mkfifo(path.c_str(),0600);
00038     if(res != 0) {
00039         std::cerr << "could not make fifo at '" << path << "'\n";
00040     }
00041 
00042     fd_ = open(path.c_str(),O_RDONLY|O_NONBLOCK);
00043 
00044     if(fd_ == -1) {
00045         std::cerr << "failed to open fifo at '" << path << "'\n";
00046     } else {
00047         std::cerr << "opened fifo at '" << path << "'. Server commands may be written to this file.\n";
00048     }
00049 #endif
00050 }
00051 
00052 input_stream::~input_stream()
00053 {
00054 #ifndef _WIN32
00055     stop();
00056 #endif
00057 }
00058 
00059 void input_stream::stop()
00060 {
00061 #ifndef _WIN32
00062     if(fd_ != -1) {
00063         close(fd_);
00064         unlink(path_.c_str());
00065         fd_ = -1;
00066     }
00067 #endif
00068 }
00069 
00070 bool input_stream::read_line(std::string& str)
00071 {
00072 #ifndef _WIN32
00073     if(fd_ == -1) {
00074         return false;
00075     }
00076 
00077     const size_t block_size = 4096;
00078     char block[block_size];
00079 
00080     const size_t nbytes = read(fd_,block,block_size);
00081     std::copy(block,block+nbytes,std::back_inserter(data_));
00082 
00083     const std::deque<char>::iterator itor = std::find(data_.begin(),data_.end(),'\n');
00084     if(itor != data_.end()) {
00085         str.resize(itor - data_.begin());
00086         std::copy(data_.begin(),itor,str.begin());
00087         data_.erase(data_.begin(),itor+1);
00088         return true;
00089     } else {
00090         return false;
00091     }
00092 #else
00093     return false;
00094 #endif
00095 }

Generated by doxygen 1.5.5 on 23 May 2008 for The Battle for Wesnoth
Gna! | Forum | Wiki | CIA | devdocs