static bool TruncateFileDefault(Stream& file, uint64 size) { // Default implementation // Getting the current end of file if (not file.seekFromEndOfFile(0)) return false; ssize_t end = (ssize_t) file.tell(); # ifndef YUNI_OS_MSVC bool result = (0 == ::ftruncate(FILENO(file.nativeHandle()), (off_t) size)); # else bool result = (0 == _chsize_s(FILENO(file.nativeHandle()), (sint64) size)); # endif if (result) { // if the file was already bigger than the new size, there is nothing to do if ((uint64)end >= size) return true; if (not file.seekFromBeginning(end)) return false; enum { bufferSize = 1024 * 1024 }; size -= (uint64) end; if (size) { char* zero = new char[bufferSize]; (void)::memset(zero, '\0', sizeof(char) * bufferSize); while (size > bufferSize) { if (bufferSize != file.write(zero, bufferSize)) { delete[] zero; return false; } size -= bufferSize; } if (size) { if (size != file.write(zero, size)) { delete[] zero; return false; } } delete[] zero; } return true; } return false; }
bool QFile::open( int m, FILE *f ) { if ( isOpen() ) { #if defined(CHECK_RANGE) qWarning( "QFile::open: File already open" ); #endif return FALSE; } init(); setMode( m &~IO_Raw ); setState( IO_Open ); fh = f; ext_f = TRUE; STATBUF st; FSTAT( FILENO(fh), &st ); ioIndex = (int)ftell( fh ); if ( (st.st_mode & STAT_MASK) != STAT_REG || f == stdin ) { //stdin is non seekable // non-seekable setType( IO_Sequential ); length = INT_MAX; } else { length = (int)st.st_size; if ( !(flags()&IO_Truncate) && length == 0 && isReadable() ) { // try if you can read from it (if you can, it's a sequential // device; e.g. a file in the /proc filesystem) int c = getch(); if ( c != -1 ) { ungetch(c); setType( IO_Sequential ); length = INT_MAX; } } } return TRUE; }
bool QFile::open( int m, FILE *f ) { if ( isOpen() ) { #if defined(CHECK_RANGE) warning( "QFile::open: File already open" ); #endif return FALSE; } init(); setMode( m &~IO_Raw ); setState( IO_Open ); fh = f; ext_f = TRUE; STATBUF st; FSTAT( FILENO(fh), &st ); index = (int)ftell( fh ); if ( (st.st_mode & STAT_MASK) != STAT_REG ) { // non-seekable setType( IO_Sequential ); length = INT_MAX; } else { length = (int)st.st_size; } return TRUE; }
s_paus(char *s, ftnlen n) #endif { fprintf(stderr, "PAUSE "); if(n > 0) fprintf(stderr, " %.*s", (int)n, s); fprintf(stderr, " statement executed\n"); if( ISATTY(FILENO(stdin)) ) s_1paus(stdin); else { #ifdef MSDOS FILE *fin; fin = fopen("con", "r"); if (!fin) { fprintf(stderr, "s_paus: can't open con!\n"); fflush(stderr); exit(1); } s_1paus(fin); fclose(fin); #else fprintf(stderr, "To resume execution, execute a kill -%d %d command\n", PAUSESIG, getpid() ); signal1(PAUSESIG, waitpause); fflush(stderr); pause(); #endif } fprintf(stderr, "Execution resumes after PAUSE.\n"); fflush(stderr); return 0; /* NOT REACHED */ #ifdef __cplusplus }
int fseek(FILE *iop, long offset, int ptrname) { off_t p; rmutex_t *lk; FLOCKFILE(lk, iop); iop->_flag &= ~_IOEOF; if (!(iop->_flag & _IOREAD) && !(iop->_flag & (_IOWRT | _IORW))) { errno = EBADF; FUNLOCKFILE(lk); return (-1); } if (iop->_flag & _IOREAD) { if (ptrname == 1 && iop->_base && !(iop->_flag&_IONBF)) { offset -= iop->_cnt; } } else if (iop->_flag & (_IOWRT | _IORW)) { if (_fflush_u(iop) == EOF) { FUNLOCKFILE(lk); return (-1); } } iop->_cnt = 0; iop->_ptr = iop->_base; if (iop->_flag & _IORW) { iop->_flag &= ~(_IOREAD | _IOWRT); } p = lseek(FILENO(iop), (off_t)offset, ptrname); FUNLOCKFILE(lk); return ((p == (off_t)-1) ? -1: 0); }
int QFile::handle() const { if ( !isOpen() ) return -1; else if ( fh ) return FILENO( fh ); else return fd; }
uint QFile::size() const { STATBUF st; if ( isOpen() ) FSTAT( fh ? FILENO(fh) : fd, &st ); else STAT( fn, &st ); return st.st_size; }
bool Stream::lockExclusive() { # ifndef YUNI_OS_WINDOWS return pFd ? (0 == flock(FILENO(pFd), LOCK_EX)) : false; # else // warning The implementation is missing on Windows (#346) assert("Stream::lock: the implementation is missing on Windows, see ticket #346"); return false; # endif }
explicit Gnuplot(const std::string cmd = "gnuplot") : boost::iostreams::stream<boost::iostreams::file_descriptor_sink>( FILENO(pout = POPEN(cmd.c_str(), "w")), boost::iostreams::never_close_handle), pout(pout), // keeps '-Weff++' quiet gp_pty(NULL), debug_messages(false) { *this << std::scientific << std::setprecision(18); // refer <iomanip> }
uint QFile::size() const { STATBUF st; if ( isOpen() ) { FSTAT( fh ? FILENO(fh) : fd, &st ); } else { STAT( QFile::encodeName(fn), &st ); } return st.st_size; }
void Stream::unlock() { # ifndef YUNI_OS_WINDOWS if (pFd) flock(FILENO(pFd), LOCK_UN); # else // warning The implementation is missing on Windows (#346) assert("Stream::lock: the implementation is missing on Windows, see ticket #346"); # endif }
static char * __getpass(const char *prompt, int size) { struct termio ttyb; unsigned short flags; char *p; int c; FILE *fi; char *pbuf = tsdalloc(_T_GETPASS, MAXPASSWD + 1, NULL); void (*sig)(int); rmutex_t *lk; if (pbuf == NULL || (fi = fopen("/dev/tty", "rF")) == NULL) return (NULL); setbuf(fi, NULL); sig = signal(SIGINT, catch); intrupt = 0; (void) ioctl(FILENO(fi), TCGETA, &ttyb); flags = ttyb.c_lflag; ttyb.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL); (void) ioctl(FILENO(fi), TCSETAF, &ttyb); FLOCKFILE(lk, stderr); (void) fputs(prompt, stderr); p = pbuf; while (!intrupt && (c = GETC(fi)) != '\n' && c != '\r' && c != EOF) { if (p < &pbuf[ size ]) *p++ = (char)c; } *p = '\0'; ttyb.c_lflag = flags; (void) ioctl(FILENO(fi), TCSETAW, &ttyb); (void) PUTC('\n', stderr); FUNLOCKFILE(lk); (void) signal(SIGINT, sig); (void) fclose(fi); if (intrupt) (void) kill(getpid(), SIGINT); return (pbuf); }
const CHR *AudioIO::detectSourceType(const CHR *const fileName, const bool verbose) { if (verbose) { PRINT_NFO(TXT("------- Audio I/O -------")); } uint8_t type = AUDIO_LIB_NULL; const bool bStdIn = (STRCASECMP(fileName, TXT("-")) == 0); if (bStdIn || PATH_ISREG(fileName)) { if (FILE *const file = bStdIn ? stdin : FOPEN(fileName, TXT("rb"))) { if (FD_ISREG(FILENO(file))) { for (size_t i = 0; g_audioIO_mapping[i].id; ++i) { if (verbose) { PRINT2_NFO(TXT("Trying input module ") FMT_CHR TXT("..."), g_audioIO_mapping[i].name); } if (checkFileType(g_audioIO_mapping[i].checkFileType, file)) { type = g_audioIO_mapping[i].id; if (verbose) { PRINT_NFO(TXT("succeeded.")); } break; } } } if (!bStdIn) { fclose(file); } } } if (verbose) { if(type == AUDIO_LIB_NULL) { PRINT_NFO(TXT("No suitable input module found -> falling back to default!")); } PRINT_NFO(TXT("------- Audio I/O -------\n")); } return getLibName(type); }
bool Stream::truncate(uint64 size, bool ensureAllocation) { if (pFd) { int fd = FILENO(pFd); if (not ensureAllocation) { # ifndef YUNI_OS_MSVC return (0 == ::ftruncate(fd, (off_t) size)); # else return (0 == _chsize_s(fd, (sint64) size)); # endif } else { # ifdef YUNI_HAS_POSIX_FALLOCATE return (0 == posix_fallocate(fd, 0, (off_t) size)); # else # ifdef YUNI_OS_MAC // On OS X, we can use fcntl(F_PREALLOCATE) to emulate posix_fallocate // (but ftruncate must be called anyway) fstore_t store; memset(&store, 0, sizeof(store)); store.fst_flags = F_ALLOCATECONTIG; store.fst_posmode = F_PEOFPOSMODE; store.fst_length = (off_t) size; if (-1 == fcntl(fd, F_PREALLOCATE, &store)) { // OK, perhaps we are too fragmented, allocate non-continuous store.fst_flags = F_ALLOCATEALL; if (-1 == fcntl(fd, F_PREALLOCATE, &store)) return false; } return (0 == ::ftruncate(fd, (off_t) size)); # else return TruncateFileDefault(*this, size); # endif // OS X # endif // POSIX_FALLOCATE } } return false; }
/* * TermInfo.tiocgwinsz(io) => [row, col] * * TermInfo.tiocgwinsz returns the screen size of the terminal refered by io, * using TIOCGWINSZ ioctl. */ static VALUE rt_tiocgwinsz(VALUE self, VALUE io) { #ifdef TIOCGWINSZ rb_io_t *fptr; struct winsize sz; int ret; GetOpenFile(io, fptr); ret = ioctl(FILENO(fptr), TIOCGWINSZ, &sz); if (ret == -1) rb_raise(rb_eIOError, "TIOCGWINSZ failed"); return rb_ary_new3(2, INT2NUM(sz.ws_row), INT2NUM(sz.ws_col)); #else rb_notimplement(); #endif }
MARPAWRAPPER_EXPORT void _genericLogger_defaultCallback(const void *userDatavp, const genericLoggerLevel_t leveli, const char *msgs) { /* We are NOT going to do a general log4c mechanism (this can come later) */ /* I.e. we are fixing the default output to be: DD/MM/YYYY hh::mm::ss PREFIX MESSAGE */ const char *prefixs = (leveli == GENERICLOGGER_LOGLEVEL_TRACE ) ? "TRACE" : (leveli == GENERICLOGGER_LOGLEVEL_DEBUG ) ? "DEBUG" : (leveli == GENERICLOGGER_LOGLEVEL_INFO ) ? "INFO" : (leveli == GENERICLOGGER_LOGLEVEL_NOTICE ) ? "NOTICE" : (leveli == GENERICLOGGER_LOGLEVEL_WARNING ) ? "WARNING" : (leveli == GENERICLOGGER_LOGLEVEL_ERROR ) ? "ERROR" : (leveli == GENERICLOGGER_LOGLEVEL_CRITICAL ) ? "CRITICAL" : (leveli == GENERICLOGGER_LOGLEVEL_ALERT ) ? "ALERT" : (leveli == GENERICLOGGER_LOGLEVEL_EMERGENCY) ? "EMERGENCY" : "UNKOWN"; char *dates = dateBuilder("%d/%m/%Y %H:%M:%S"); char *localMsgs = messageBuilder("%s %9s %s\n", dates, prefixs, (msgs != NULL) ? (char *) msgs : (char *) GENERICLOGGER_LOG_NO_MESSAGE); char *p = localMsgs; #ifdef FILENO int filenoStderr = FILENO(stderr); #ifdef SYS_FILENO_IS_FILENO ssize_t bytesWriten = 0; #else size_t bytesWriten = 0; #endif size_t count; #endif #ifdef FILENO count = strlen(p); while (bytesWriten < count) { bytesWriten += SYS_WRITE(filenoStderr, p+bytesWriten, count-bytesWriten); } #else /* Note: this is not asynchroneous safe */ fprintf(stderr, "%s", p); #endif if (dates != dateBuilder_internalErrors()) { free(dates); } if (localMsgs != messageBuilder_internalErrors()) { free(localMsgs); } }
/* * TermInfo.tiocswinsz(io, row, col) * * TermInfo.tiocgwinsz update the screen size information of the terminal refered by io, * using TIOCSWINSZ ioctl. * * It returns nil. */ static VALUE rt_tiocswinsz(VALUE self, VALUE io, VALUE row, VALUE col) { #ifdef TIOCSWINSZ rb_io_t *fptr; struct winsize sz; int ret; GetOpenFile(io, fptr); sz.ws_row = NUM2INT(row); sz.ws_col = NUM2INT(col); ret = ioctl(FILENO(fptr), TIOCSWINSZ, &sz); if (ret == -1) rb_raise(rb_eIOError, "TIOCSWINSZ failed"); return Qnil; #else rb_notimplement(); #endif }
int CStdLibFileIO::GetHandle() { return FILENO(m_pFile); }
uint QFile::size() const { STATBUF st; if ( isOpen() ) { FSTAT( fh ? FILENO(fh) : fd, &st ); return st.st_size; } else { #if defined(__CYGWIN32_) STAT( QFile::encodeName(fn), &st ); #else QString str = fn; reslashify(str); #ifdef QT_LARGEFILE_SUPPORT if ( _wstati64( (wchar_t*) str.ucs2(), &st ) != -1 ) { #else if ( _wstat( (wchar_t*) str.ucs2(), &st ) != -1 ) { #endif #endif return st.st_size; } } return 0; } /*! \fn int QFile::at() const Returns the file index. \sa size() */ /*! Sets the file index to \e pos. Returns TRUE if successful, otherwise FALSE. Example: \code QFile f( "data.bin" ); f.open( IO_ReadOnly ); // index set to 0 f.at( 100 ); // set index to 100 f.at( f.at()+50 ); // set index to 150 f.at( f.size()-80 ); // set index to 80 before EOF f.close(); \endcode \warning The result is undefined if the file was \link open() opened\endlink using the \c IO_Append specifier. \sa size(), open() */ bool QFile::at( int pos ) { if ( !isOpen() ) { #if defined(CHECK_STATE) qWarning( "QFile::at: File is not open" ); #endif return FALSE; } bool ok; if ( isRaw() ) { // raw file pos = (int)LSEEK(fd, pos, SEEK_SET); ok = pos != -1; } else { // buffered file ok = fseek(fh, pos, SEEK_SET) == 0; } if ( ok ) ioIndex = pos; #if defined(CHECK_RANGE) else qWarning( "QFile::at: Cannot set file position %d", pos ); #endif return ok; } /*! Reads at most \e len bytes from the file into \e p and returns the number of bytes actually read. Returns -1 if a serious error occurred. \warning We have experienced problems with some C libraries when a buffered file is opened for both reading and writing. If a read operation takes place immediately after a write operation, the read buffer contains garbage data. Worse, the same garbage is written to the file. Calling flush() before readBlock() solved this problem. \sa writeBlock() */ int QFile::readBlock( char *p, uint len ) { #if defined(CHECK_NULL) if ( !p ) qWarning( "QFile::readBlock: Null pointer error" ); #endif #if defined(CHECK_STATE) if ( !isOpen() ) { // file not open qWarning( "QFile::readBlock: File not open" ); return -1; } if ( !isReadable() ) { // reading not permitted qWarning( "QFile::readBlock: Read operation not permitted" ); return -1; } #endif int nread; // number of bytes read if ( isRaw() ) { // raw file nread = READ( fd, p, len ); if ( len && nread <= 0 ) { nread = 0; setStatus(IO_ReadError); } } else { // buffered file nread = (int)fread( p, 1, len, fh ); if ( (uint)nread != len ) { if ( ferror( fh ) || nread==0 ) setStatus(IO_ReadError); } } ioIndex += nread; return nread; } /*! \overload int writeBlock( const QByteArray& data ) */ /*! \reimp Writes \e len bytes from \e p to the file and returns the number of bytes actually written. Returns -1 if a serious error occurred. \warning When working with buffered files, data may not be written to the file at once. Call flush() to make sure the data is really written. \sa readBlock() */ int QFile::writeBlock( const char *p, uint len ) { #if defined(CHECK_NULL) if ( p == 0 && len != 0 ) qWarning( "QFile::writeBlock: Null pointer error" ); #endif #if defined(CHECK_STATE) if ( !isOpen() ) { // file not open qWarning( "QFile::writeBlock: File not open" ); return -1; } if ( !isWritable() ) { // writing not permitted qWarning( "QFile::writeBlock: Write operation not permitted" ); return -1; } #endif int nwritten; // number of bytes written if ( isRaw() ) // raw file nwritten = WRITE( fd, p, len ); else // buffered file nwritten = (int)fwrite( p, 1, len, fh ); if ( nwritten != (int)len ) { // write error if ( errno == ENOSPC ) // disk is full setStatus( IO_ResourceError ); else setStatus( IO_WriteError ); if ( isRaw() ) // recalc file position ioIndex = (int)LSEEK( fd, 0, SEEK_CUR ); else ioIndex = fseek( fh, 0, SEEK_CUR ); } else { ioIndex += nwritten; } if ( ioIndex > length ) // update file length length = ioIndex; return nwritten; } /*! Returns the file handle of the file. This is a small positive integer, suitable for use with C library functions such as fdopen() and fcntl(), as well as with QSocketNotifier. If the file is not open or there is an error, handle() returns -1. \sa QSocketNotifier */ int QFile::handle() const { if ( !isOpen() ) return -1; else if ( fh ) return FILENO( fh ); else return fd; } /*! Closes an open file. The file is not closed if it was opened with an existing file handle. If the existing file handle is a \c FILE*, the file is flushed. If the existing file handle is an \c int file descriptor, nothing is done to the file. Some "write-behind" filesystems may report an unspecified error on closing the file. These errors only indicate that something may have gone wrong since the previous open(). In such a case status() reports IO_UnspecifiedError after close(), otherwise IO_Ok. \sa open(), flush() */ void QFile::close() { bool ok = FALSE; if ( isOpen() ) { // file is not open if ( fh ) { // buffered file if ( ext_f ) ok = fflush( fh ) != -1; // flush instead of closing else ok = fclose( fh ) != -1; } else { // raw file if ( ext_f ) ok = TRUE; // cannot close else ok = CLOSE( fd ) != -1; } init(); // restore internal state } if (!ok) setStatus (IO_UnspecifiedError); return; }
bool QFile::open( int m ) { if ( isOpen() ) { // file already open #if defined(CHECK_STATE) qWarning( "QFile::open: File already open" ); #endif return FALSE; } if ( fn.isNull() ) { // no file name defined #if defined(CHECK_NULL) qWarning( "QFile::open: No file name specified" ); #endif return FALSE; } init(); // reset params setMode( m ); if ( !(isReadable() || isWritable()) ) { #if defined(CHECK_RANGE) qWarning( "QFile::open: File access not specified" ); #endif return FALSE; } bool ok = TRUE; STATBUF st; if ( isRaw() ) { // raw file I/O int oflags = OPEN_RDONLY; if ( isReadable() && isWritable() ) oflags = OPEN_RDWR; else if ( isWritable() ) oflags = OPEN_WRONLY; if ( flags() & IO_Append ) { // append to end of file? if ( flags() & IO_Truncate ) oflags |= (OPEN_CREAT | OPEN_TRUNC); else oflags |= (OPEN_APPEND | OPEN_CREAT); setFlags( flags() | IO_WriteOnly ); // append implies write } else if ( isWritable() ) { // create/trunc if writable if ( flags() & IO_Truncate ) oflags |= (OPEN_CREAT | OPEN_TRUNC); else oflags |= OPEN_CREAT; } #if defined(HAS_TEXT_FILEMODE) if ( isTranslated() ) oflags |= OPEN_TEXT; else oflags |= OPEN_BINARY; #endif #if defined(HAS_ASYNC_FILEMODE) if ( isAsynchronous() ) oflags |= OPEN_ASYNC; #endif fd = OPEN( QFile::encodeName(fn), oflags, 0666 ); if ( fd != -1 ) { // open successful FSTAT( fd, &st ); // get the stat for later usage } else { ok = FALSE; } } else { // buffered file I/O QCString perm; char perm2[4]; bool try_create = FALSE; if ( flags() & IO_Append ) { // append to end of file? setFlags( flags() | IO_WriteOnly ); // append implies write perm = isReadable() ? "a+" : "a"; } else { if ( isReadWrite() ) { if ( flags() & IO_Truncate ) { perm = "w+"; } else { perm = "r+"; try_create = TRUE; // try to create if not exists } } else if ( isReadable() ) { perm = "r"; } else if ( isWritable() ) { perm = "w"; } } qstrcpy( perm2, perm ); #if defined(HAS_TEXT_FILEMODE) if ( isTranslated() ) strcat( perm2, "t" ); else strcat( perm2, "b" ); #endif while (1) { // At most twice fh = fopen( QFile::encodeName(fn), perm2 ); if ( !fh && try_create ) { perm2[0] = 'w'; // try "w+" instead of "r+" try_create = FALSE; } else { break; } } if ( fh ) { FSTAT( FILENO(fh), &st ); // get the stat for later usage } else { ok = FALSE; } } if ( ok ) { setState( IO_Open ); // on successful open the file stat was got; now test what type // of file we have if ( (st.st_mode & STAT_MASK) != STAT_REG ) { // non-seekable setType( IO_Sequential ); length = INT_MAX; ioIndex = (flags() & IO_Append) == 0 ? 0 : length; } else { length = (int)st.st_size; ioIndex = (flags() & IO_Append) == 0 ? 0 : length; if ( !(flags()&IO_Truncate) && length == 0 && isReadable() ) { // try if you can read from it (if you can, it's a sequential // device; e.g. a file in the /proc filesystem) int c = getch(); if ( c != -1 ) { ungetch(c); setType( IO_Sequential ); length = INT_MAX; } } } } else { init(); if ( errno == EMFILE ) // no more file handles/descrs setStatus( IO_ResourceError ); else setStatus( IO_OpenError ); } return ok; }
bool QFile::open( int m ) { if ( isOpen() ) { // file already open #if defined(CHECK_STATE) warning( "QFile::open: File already open" ); #endif return FALSE; } if ( fn.isNull() ) { // no file name defined #if defined(CHECK_NULL) warning( "QFile::open: No file name specified" ); #endif return FALSE; } init(); // reset params setMode( m ); if ( !(isReadable() || isWritable()) ) { #if defined(CHECK_RANGE) warning( "QFile::open: File access not specified" ); #endif return FALSE; } bool ok = TRUE; if ( isRaw() ) { // raw file I/O int oflags = OPEN_RDONLY; if ( isReadable() && isWritable() ) oflags = OPEN_RDWR; else if ( isWritable() ) oflags = OPEN_WRONLY; if ( flags() & IO_Append ) { // append to end of file? if ( flags() & IO_Truncate ) oflags |= (OPEN_CREAT | OPEN_TRUNC); else oflags |= (OPEN_APPEND | OPEN_CREAT); setFlags( flags() | IO_WriteOnly ); // append implies write } else if ( isWritable() ) { // create/trunc if writable if ( flags() & IO_Truncate ) oflags |= (OPEN_CREAT | OPEN_TRUNC); else oflags |= OPEN_CREAT; } #if defined(HAS_TEXT_FILEMODE) && !defined(_OS_MAC_) if ( isTranslated() ) oflags |= OPEN_TEXT; else oflags |= OPEN_BINARY; #endif #if defined(HAS_ASYNC_FILEMODE) if ( isAsynchronous() ) oflags |= OPEN_ASYNC; #endif fd = OPEN( (const char *)fn, oflags, 0666 ); if ( fd != -1 ) { // open successful STATBUF st; FSTAT( fd, &st ); length = (int)st.st_size; index = (flags() & IO_Append) == 0 ? 0 : length; } else { ok = FALSE; } } else { // buffered file I/O const char *perm = 0; char perm2[4]; bool try_create = FALSE; if ( flags() & IO_Append ) { // append to end of file? setFlags( flags() | IO_WriteOnly ); // append implies write perm = isReadable() ? "a+" : "a"; } else { if ( isReadWrite() ) { if ( flags() & IO_Truncate ) { perm = "w+"; } else { perm = "r+"; try_create = TRUE; // try to create if not exists } } else if ( isReadable() ) { perm = "r"; } else if ( isWritable() ) { perm = "w"; } } strcpy( perm2, perm ); #if defined(HAS_TEXT_FILEMODE) if ( isTranslated() ) strcat( perm2, "t" ); else strcat( perm2, "b" ); #endif fh = fopen( (const char *)fn, perm2 ); if ( !fh && try_create ) { perm2[0] = 'w'; // try "w+" instead of "r+" fh = fopen( (const char *)fn, perm2 ); } if ( fh ) { STATBUF st; FSTAT( FILENO(fh), &st ); length = (int)st.st_size; index = (flags() & IO_Append) == 0 ? 0 : length; } else { ok = FALSE; } } if ( ok ) { setState( IO_Open ); } else { init(); if ( errno == EMFILE ) // no more file handles/descrs setStatus( IO_ResourceError ); else setStatus( IO_OpenError ); } return ok; }
char* MemoryMapping::map(char* buffer, int buffersize, FILE* file, int offset) { #ifdef _MSC_VER HANDLE filehandle = (HANDLE) _get_osfhandle(FILENO(file)); HANDLE filemapping = ::CreateFileMappingA( filehandle, &MMAP_SECURITY_ATTRIBUTES, PAGE_READONLY | SEC_COMMIT, 0, 0, 0); if (0 == filemapping) return MAP_FAILED; DWORD alignedoffset = (offset / getPageSize()) * getPageSize(); DWORD alignment = offset - alignedoffset; LPVOID mappedmemory = ::MapViewOfFile( filemapping, FILE_MAP_READ, 0, alignedoffset, 0); ::CloseHandle(filemapping); if (0 != mappedmemory) { return ((char*) mappedmemory) + alignment; } else { return 0; } #else int filehandle = FILENO(file); int protection = PROT_READ; int flags = MAP_PRIVATE; int alignedoffset = (offset / getpagesize()) * getpagesize(); int alignment = offset - alignedoffset; int alignedlength = ((buffersize / getpagesize()) + 1) * getpagesize(); char* result = (char*) ::mmap( (void*) buffer, alignedlength, protection, flags, filehandle, alignedoffset); return ((char*) -1) == result ? 0 : result + alignment; #endif }