void Directory::open(const std::string& path_, bool lazyread_) { #ifdef WIN32 std::string tmp(path_); if (tmp.size() + 1 + 3 >= _MAX_PATH) throw std::runtime_error("pvpgn::Directory::Directory(): WIN32: path too long"); tmp += "/*.*"; status = 0; std::memset(&fileinfo, 0, sizeof(fileinfo)); lFindHandle = _findfirst(tmp.c_str(), &fileinfo); if (lFindHandle < 0 && !lazyread_) throw OpenError(tmp); path = tmp; #else /* POSIX style */ if (!(dir = opendir(path_.c_str())) && !lazyread_) throw OpenError(path); path = path_; #endif /* WIN32-POSIX */ lazyread = lazyread_; }
void StandardFile::openFile(const char* fileName,File::AccessMode accessMode,int flags,int mode) { /* Adjust flags according to access mode: */ switch(accessMode) { case None: flags&=~(O_RDONLY|O_WRONLY|O_RDWR|O_CREAT|O_TRUNC|O_APPEND); break; case ReadOnly: flags&=~(O_WRONLY|O_RDWR|O_CREAT|O_TRUNC|O_APPEND); flags|=O_RDONLY; break; case WriteOnly: flags&=~(O_RDONLY|O_RDWR); flags|=O_WRONLY; break; case ReadWrite: flags&=~(O_RDONLY|O_WRONLY); flags|=O_RDWR; break; } /* Open the file: */ fd=open(fileName,flags,mode); /* Check for errors and throw an exception: */ if(fd<0) { int errorCode=errno; throw OpenError(Misc::printStdErrMsg("IO::StandardFile: Unable to open file %s for %s due to error %d",fileName,getAccessModeName(accessMode),errorCode)); } }
ClusterFileCharacterSource::ClusterFileCharacterSource(const char* inputFileName,MulticastPipe* sPipe,size_t sBufferSize) :CharacterSource(sBufferSize), inputFd(-1), pipe(sPipe) { bool ok; if(pipe==0||pipe->isMaster()) { /* Open the input file: */ inputFd=open(inputFileName,O_RDONLY); ok=inputFd>=0; if(pipe!=0) { /* Send an error indicator to the slaves: */ pipe->write<int>(ok?1:0); pipe->finishMessage(); } } else { /* Receive the error indicator from the master: */ ok=pipe->read<int>()!=0; } if(!ok) throw OpenError(Misc::printStdErrMsg("ClusterFileCharacterSource: Error while opening input file %s",inputFileName)); }
StandardDirectorySlave::StandardDirectorySlave(Multiplexer* sMultiplexer,const char* sPathName,int) :StandardDirectory(sMultiplexer,sPathName,0) { /* Check for failure: */ if(pipe.read<char>()==0) throw OpenError(pathName.c_str()); }
GzippedFile::GzippedFile(const char* inputFileName) :File(ReadOnly), inputFile(0) { /* Open the compressed input file: */ if((inputFile=gzopen(inputFileName,"r"))==0) throw OpenError(Misc::printStdErrMsg("IO::GzippedFile: Error while opening gzipped input file %s",inputFileName)); }
StandardDirectory::StandardDirectory(std::string sPathName,int) :pathName(sPathName), directory(opendir(pathName.c_str())), entry(0) { /* Check for failure: */ if(directory==0) throw OpenError(pathName.c_str()); }
void Pololu::Serial::Interface::open() { if (!handle) { handle = ::open(address.c_str(), O_RDWR | O_NDELAY); if (handle > 0) setup(); else throw OpenError(address); } }
StandardDirectoryMaster::StandardDirectoryMaster(Multiplexer* sMultiplexer,const char* sPathName,int) :StandardDirectory(sMultiplexer,sPathName,0), directory(opendir(pathName.c_str())), entry(0) { /* Check for failure: */ pipe.write<char>(directory!=0?1:0); pipe.flush(); if(directory==0) throw OpenError(pathName.c_str()); }
GzippedFileCharacterSource::GzippedFileCharacterSource(const char* inputFileName,size_t sBufferSize) :Misc::CharacterSource(sBufferSize), inputFile(0),halfBufferSize(bufferSize/2), numFilledBuffers(0),encounteredReadError(2),nextReadBuffer(0),haveReadBuffers(false) { /* Open the compressed input file: */ if((inputFile=gzopen(inputFileName,"r"))==0) throw OpenError(Misc::printStdErrMsg("GzippedFileCharacterSource: Error while opening gzipped input file %s",inputFileName)); /* Start the readahead thread: */ readAheadThread.start(this,&GzippedFileCharacterSource::readAheadThreadMethod); }
void * next_dlsym(void *handle, char *symbol) { NXStream *errorStream = OpenError(); char symbuf[1024]; unsigned long symref = 0; snprintf(symbuf, sizeof(symbuf), "_%s", symbol); if (!rld_lookup(errorStream, symbuf, &symref)) TransferError(errorStream); CloseError(errorStream); return (void *) symref; }
/// \return false if !closed() void open(const boost::filesystem::path &path) { try { if (!closed()) { BOOST_THROW_EXCEPTION(OpenedError()); } path_ = path; stream_ = openFd(path, errno_); checkError(); } catch (std::exception &) { BOOST_THROW_EXCEPTION(OpenError() << enable_nested_current()); } }
SerialPort::SerialPort(const char* deviceName) :Pipe(ReadWrite), fd(-1) { /* Open the device file: */ fd=open(deviceName,O_RDWR|O_NOCTTY); if(fd<0) throw OpenError(Misc::printStdErrMsg("Comm::SerialPort: Unable to open device %s",deviceName)); /* Configure as "raw" port: */ struct termios term; tcgetattr(fd,&term); cfmakeraw(&term); term.c_iflag|=IGNBRK; // Don't generate signals term.c_cflag|=CREAD|CLOCAL; // Enable receiver; no modem line control term.c_cc[VMIN]=1; // Block read() until at least a single byte is read term.c_cc[VTIME]=0; // No timeout on read() if(tcsetattr(fd,TCSANOW,&term)!=0) throw OpenError(Misc::printStdErrMsg("Comm::SerialPort: Unable to configure device %s",deviceName)); /* Flush both queues: */ tcflush(fd,TCIFLUSH); tcflush(fd,TCOFLUSH); }
void Create(Tar *tar) { int fdTar, ndx, pid; DIR *dir; char *buf; fdTar = open(tar->tarfile, O_CREAT | O_TRUNC | O_WRONLY, PERM); if (fdTar < 0) { OpenError(tar->tarfile, fdTar); exit(EXIT_FAILURE); } for (ndx = 0; ndx < tar->numFiles; ndx++) { dir = opendir(tar->files[ndx]); if (dir != NULL) { buf = calloc(strlen(tar->files[ndx]) + 2, sizeof(char)); if (tar->files[ndx][strlen(tar->files[ndx]) - 1] != '/') sprintf(buf, "%s/", tar->files[ndx]); else strcpy(buf, tar->files[ndx]); CreateDirectory(tar, fdTar, buf, dir); closedir(dir); free(buf); } else { CreateFile(tar, fdTar, tar->files[ndx]); } } close(fdTar); if (tar->opts[Z_FLAG]) { pid = fork(); if (pid == 0) { if (tar->opts[V_FLAG]) printf("Compressing '%s'\n", tar->tarfile); execlp(COMPRESSION, COMPRESSION, "-9", tar->tarfile, NULL); perror("exec failed"); exit(EXIT_FAILURE); } wait(NULL); } }
void CreateFile(Tar *tar, int fdTar, char *name) { int fdFile, size; struct stat statbuf[sizeof(stat) + 1]; char buf[BUF_SIZE]; if (tar->numHeaders >= MAX_FILES) { printf("maximm number of files reached\n"); exit(EXIT_SUCCESS); } if (strlen(name) >= H_NAME) { fprintf(stderr, "file name/path cannot exceed %d, given %u\n", H_NAME, strlen(name)); return; } fdFile = open(name, O_RDONLY); if (fdFile < 0) { OpenError(name, fdFile); close(fdFile); return; } if (fstat(fdFile, statbuf) != 0) { perror("stat error"); exit(EXIT_FAILURE); } CreateHeader(tar, statbuf, name, TYPE_FILE); write(fdTar, tar->headers[tar->numHeaders], sizeof(Header)); tar->numHeaders++; while ((size = read(fdFile, buf, BUF_SIZE)) != 0) write(fdTar, buf, size); if (tar->opts[V_FLAG]) printf("Added file '%s'\n", name); close(fdFile); }
StandardDirectory::StandardDirectory(std::string sPathName) :directory(0), entry(0) { /* Prepend the current directory path to the path name if the given path name is relative: */ if(sPathName.empty()||sPathName[0]!='/') { pathName=Misc::getCurrentDirectory(); pathName.push_back('/'); pathName.append(sPathName); } else pathName=sPathName; /* Normalize the path name and open the directory: */ normalizePath(pathName,1); directory=opendir(pathName.c_str()); /* Check for failure: */ if(directory==0) throw OpenError(pathName.c_str()); }
void * next_dlopen(char *name) { int rld_success; NXStream *errorStream; char *result = NULL; char **p; errorStream = OpenError(); p = calloc(2, sizeof(void *)); p[0] = name; rld_success = rld_load(errorStream, NULL, p, NULL); free(p); if (!rld_success) { TransferError(errorStream); result = (char *) 1; } CloseError(errorStream); return result; }
void HttpFile::init(const HttpFile::URLParts& urlParts) { /* Assemble the GET request: */ std::string request; request.append("GET"); request.push_back(' '); request.append(urlParts.resourcePath); request.push_back(' '); request.append("HTTP/1.1\r\n"); request.append("Host: "); request.append(urlParts.serverName); request.push_back(':'); int pn=urlParts.portNumber; char buf[10]; char* bufPtr=buf; do { *(bufPtr++)=char(pn%10+'0'); pn/=10; } while(pn!=0); while(bufPtr!=buf) request.push_back(*(--bufPtr)); request.append("\r\n"); #if 0 request.append("Accept: text/html\r\n"); #endif request.append("\r\n"); /* Send the GET request: */ pipe->writeRaw(request.data(),request.size()); pipe->flush(); /* Wait for the server's reply: */ if(!pipe->waitForData(Misc::Time(30,0))) throw OpenError(Misc::printStdErrMsg("Comm::HttpFile: Timeout while waiting for reply from server \"%s\" on port %d",urlParts.serverName.c_str(),urlParts.portNumber)); { /* Attach a value source to the pipe to parse the server's reply: */ IO::ValueSource reply(pipe); reply.setPunctuation("()<>@,;:\\/[]?={}\r"); reply.setQuotes("\""); reply.skipWs(); /* Read the status line: */ if(!reply.isLiteral("HTTP")||!reply.isLiteral('/')) throw OpenError(Misc::printStdErrMsg("Comm::HttpFile: Malformed HTTP reply from server \"%s\" on port %d",urlParts.serverName.c_str(),urlParts.portNumber)); reply.skipString(); unsigned int statusCode=reply.readUnsignedInteger(); if(statusCode!=200) throw OpenError(Misc::printStdErrMsg("Comm::HttpFile: HTTP error %d while opening resource \"%s\" on server \"%s\" on port %d",statusCode,urlParts.resourcePath.c_str(),urlParts.serverName.c_str(),urlParts.portNumber)); reply.readLine(); reply.skipWs(); /* Parse reply options until the first empty line: */ while(!reply.eof()&&reply.peekc()!='\r') { /* Read the option tag: */ std::string option=reply.readString(); if(reply.isLiteral(':')) { /* Handle the option value: */ if(option=="Transfer-Encoding") { /* Parse the comma-separated list of transfer encodings: */ while(true) { std::string coding=reply.readString(); if(coding=="chunked") chunked=true; else { /* Skip the transfer extension: */ while(reply.isLiteral(';')) { reply.skipString(); if(!reply.isLiteral('=')) throw OpenError(Misc::printStdErrMsg("Comm::HttpFile: Malformed HTTP reply from server \"%s\" on port %d",urlParts.serverName.c_str(),urlParts.portNumber)); reply.skipString(); } } if(reply.eof()||reply.peekc()!=',') break; while(!reply.eof()&&reply.peekc()==',') reply.readChar(); } } else if(option=="Content-Length") { if(!chunked) { fixedSize=true; unreadSize=reply.readUnsignedInteger(); } } } /* Skip the rest of the line: */ reply.skipLine(); reply.skipWs(); } /* Read the CR/LF pair: */ if(reply.getChar()!='\r'||reply.getChar()!='\n') throw OpenError(Misc::printStdErrMsg("Comm::HttpFile: Malformed HTTP reply from server \"%s\" on port %d",urlParts.serverName.c_str(),urlParts.portNumber)); } if(chunked) { /* Read the first chunk header: */ unreadSize=parseChunkHeader(*pipe); haveEof=unreadSize==0; } }
//------------------------------------------------------------------------------ // ConfigFile::read //------------------------------------------------------------------------------ void ConfigFile::read() { // Synchronize the function. SimpleThread_Synchronize sync(classMutex); string currentSection; char maxLine[2048]; // Line can be a maximum of 2048 characters big. char *ptr, *ptr2, *ptr3; unsigned int i; ifstream in; in.open(configFile.c_str()); // Make sure we opened the file. if (in.fail()) { string errMsg = "Unable to open the configuration file: "; errMsg += configFile.c_str(); throw OpenError(errMsg.c_str()); } // Start with the global config section. currentSection = ""; configSections.insert(ConfigSectionsPair(currentSection.c_str(), ConfigSection(currentSection)) ); // Read and process all the lines that are read in. while(in) { memset(maxLine, 0, sizeof(maxLine)); in.getline(maxLine, sizeof(maxLine)-1); // Strip any '#' comments and ignore. ptr = strchr(maxLine, '#'); if (ptr) ptr[0] = '\0'; // Make sure we have no \n or \r still in the line. ptr = strchr(maxLine, '\n'); if (ptr) ptr[0] = '\0'; ptr = strchr(maxLine, '\r'); if (ptr) ptr[0] = '\0'; // Don't waste time processing empty or too short lines. if (strlen(maxLine) > 3) { // Check if we have a new section and add it as the current section. if ((ptr = strchr(maxLine, '[')) && (ptr2 = strchr(maxLine, ']')) ) { // Get the section name. ptr += 1; ptr2[0] = '\0'; //Convert the section name to lower case for (unsigned i=0; i<strlen(ptr); i++) ptr[i] = tolower(ptr[i]); currentSection = ptr; configSections.insert(ConfigSectionsPair(currentSection.c_str(), ConfigSection(currentSection)) ); } // else do we have a name value pair. else if ((ptr = strchr(maxLine, '=')) ) { ptr3 = ptr + 1; // Point to first char after = sign for start of value. ptr[0] = '\0'; // Lets get the name and strip any leading and trailing spaces. ptr=name //Convert the name to lower case for ( i=0; i<strlen(maxLine); i++) maxLine[i] = tolower(maxLine[i]); // Leading ptr = maxLine; for ( i=0; i<strlen(maxLine); i++) if (maxLine[i] != ' ') { ptr = maxLine + i; break; } // Trailing for ( i =( unsigned int) strlen(maxLine)-1; i>=0; i--) if (maxLine[i] == ' ') maxLine[i] = '\0'; else break; // Lets get the value and strip any trailing and leading spaces. ptr2=value // Leading ptr2 = ptr3; for ( i=0; i<strlen(ptr3); i++) if (ptr3[i] != ' ') { ptr2 = ptr3 + i; break; } // Trailing for ( i = (unsigned int) strlen(ptr3)-1; i>=0; i--) if (ptr3[i] == ' ') ptr3[i] = '\0'; else break; // Now add the name value pair to the section if it is unique. ConfigSectionsIterator it = configSections.find(currentSection); ConfigSection::ValuesIterator itValue = it->second.values.find(string(ptr)); if (itValue != it->second.values.end()) { string errMsg = "The section "; errMsg += currentSection.c_str(); errMsg += " contains a duplicate key name: "; errMsg += ptr; throw DuplicateNameError(errMsg); } ConfigSection::Value val; val.value = ptr2; val.status = ConfigSection::CURRENT; it->second.values.insert( ConfigSection::ValuesPair(ptr, val) ); } //If none of the above then ignore the line. } } in.close(); } // ConfigFile::read