int fsal_dirnext(fsal_dir_handle_t hdir, unsigned short *filename, struct stat *st) { DIR_ITER *dir = (DIR_ITER *)hdir; int ret; struct _wfinddata_t filestruct; unsigned short fullname[READER_PATH_MAX]; ret = _wfindnext(dir->handle,&filestruct); if (ret != 0) { return ret; } //do not return '.' and '..' entries for simulated root dir if ((wcscmp(dir->path, root_dir_uni) == 0) //is root dir && ((wcscmp(filestruct.name, reader_path_this) == 0) || ((wcscmp(filestruct.name, reader_path_upper) == 0))) ) { return fsal_dirnext((fsal_dir_handle_t)dir, filename, st); } reader_wcscpy(filename, filestruct.name); reader_wcscpy(fullname, dir->path); reader_wcscat(fullname, L"\\"); reader_wcscat(fullname, filename); //"struct stat" and "struct _stat" are identical return _wstat(fullname, (struct _stat *)st); }
bool FileExists(CString strFilename) { struct _stat stFileInfo; bool blnReturn; int intStat; // Attempt to get the file attributes intStat = _wstat(strFilename, &stFileInfo); if (intStat == 0) { // We were able to get the file attributes // so the file obviously exists. blnReturn = true; } else { // We were not able to get the file attributes. // This may mean that we don't have permission to // access the folder which contains this file. If you // need to do that level of checking, lookup the // return values of _wstat which will give you // more details on why _wstat failed. blnReturn = false; } return(blnReturn); }
static inline int CS_stat (const char* path, struct stat* buf) { #if defined (__CYGWIN32__) return stat(path, buf); #elif defined(CS_COMPILER_MSVC) size_t pathLen (strlen (path)); size_t pathWlen (pathLen + 1); CS_ALLOC_STACK_ARRAY(wchar_t, pathW, pathWlen); csUnicodeTransform::UTF8toWC (pathW, pathWlen, (utf8_char*)path, pathLen); /* Note: the cast works as struct stat and struct _stat64i32 effectively have the same layout */ return _wstat64i32 (pathW, reinterpret_cast<struct _stat64i32*> (buf)); #else size_t pathLen (strlen (path)); size_t pathWlen (pathLen + 1); CS_ALLOC_STACK_ARRAY(wchar_t, pathW, pathWlen); csUnicodeTransform::UTF8toWC (pathW, pathWlen, (utf8_char*)path, pathLen); /* Note: the cast works as struct stat and struct _stat64i32 effectively have the same layout */ return _wstat (pathW, reinterpret_cast<struct _stat*> (buf)); #endif }
int64 DroppedFile::getSize() { #ifdef LOVE_WINDOWS // make sure non-ASCII filenames work. std::wstring wfilename = to_widestr(filename); struct _stat buf; if (_wstat(wfilename.c_str(), &buf) != 0) return -1; return (int64) buf.st_size; #else // Assume POSIX support... struct stat buf; if (stat(filename.c_str(), &buf) != 0) return -1; return (int64) buf.st_size; #endif }
int _Py_stat(PyObject *path, struct stat *statbuf) { #ifdef MS_WINDOWS int err; struct _stat wstatbuf; const wchar_t *wpath; wpath = _PyUnicode_AsUnicode(path); if (wpath == NULL) return -2; err = _wstat(wpath, &wstatbuf); if (!err) statbuf->st_mode = wstatbuf.st_mode; return err; #else int ret; PyObject *bytes; char *cpath; bytes = PyUnicode_EncodeFSDefault(path); if (bytes == NULL) return -2; /* check for embedded null bytes */ if (PyBytes_AsStringAndSize(bytes, &cpath, NULL) == -1) { Py_DECREF(bytes); return -2; } ret = stat(cpath, statbuf); Py_DECREF(bytes); return ret; #endif }
bool FileInfo::exists() { bool slashAtEnd = FileSystem::slashAtEnd( Filepath ); if ( slashAtEnd ) { FileSystem::dirRemoveSlashAtEnd(Filepath); } #if EFSW_PLATFORM != EFSW_PLATFORM_WIN32 struct stat st; int res = stat( Filepath.c_str(), &st ); #else struct _stat st; int res = _wstat( String::fromUtf8( Filepath ).toWideString().c_str(), &st ); #endif if (slashAtEnd) { FileSystem::dirAddSlashAtEnd(Filepath); } return 0 == res; }
static BOOL common_dll_prep(const wchar_t *path) { HMODULE hmod; HKEY hkey; struct _stat stat_buf; wchar_t test_path[MAX_PATH + 1]; _snwprintf(test_path, sizeof(test_path) / sizeof(wchar_t), L"%s\\libgtk-win32-2.0-0.dll", path); test_path[sizeof(test_path) / sizeof(wchar_t) - 1] = L'\0'; if (_wstat(test_path, &stat_buf) != 0) { printf("Unable to determine GTK+ path. \n" "Assuming GTK+ is in the PATH.\n"); return FALSE; } wprintf(L"GTK+ path found: %s\n", path); if ((hmod = GetModuleHandleW(L"kernel32.dll"))) { MySetDllDirectory = (LPFNSETDLLDIRECTORY) GetProcAddress( hmod, "SetDllDirectoryW"); if (!MySetDllDirectory) printf("SetDllDirectory not supported\n"); } else printf("Error getting kernel32.dll module handle\n"); /* For Windows XP SP1+ / Server 2003 we use SetDllDirectory to avoid dll hell */ if (MySetDllDirectory) { printf("Using SetDllDirectory\n"); MySetDllDirectory(path); } /* For the rest, we set the current directory and make sure * SafeDllSearch is set to 0 where needed. */ else { OSVERSIONINFOW osinfo; printf("Setting current directory to GTK+ dll directory\n"); SetCurrentDirectoryW(path); /* For Windows 2000 (SP3+) / WinXP (No SP): * If SafeDllSearchMode is set to 1, Windows system directories are * searched for dlls before the current directory. Therefore we set it * to 0. */ osinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW); GetVersionExW(&osinfo); if ((osinfo.dwMajorVersion == 5 && osinfo.dwMinorVersion == 0 && wcscmp(osinfo.szCSDVersion, L"Service Pack 3") >= 0) || (osinfo.dwMajorVersion == 5 && osinfo.dwMinorVersion == 1 && wcscmp(osinfo.szCSDVersion, L"") >= 0) ) { DWORD regval = 1; DWORD reglen = sizeof(DWORD); printf("Using Win2k (SP3+) / WinXP (No SP)... Checking SafeDllSearch\n"); read_reg_string(HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Control\\Session Manager", L"SafeDllSearchMode", (LPBYTE) ®val, ®len); if (regval != 0) { printf("Trying to set SafeDllSearchMode to 0\n"); regval = 0; if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"System\\CurrentControlSet\\Control\\Session Manager", 0, KEY_SET_VALUE, &hkey ) == ERROR_SUCCESS) { if (RegSetValueExW(hkey, L"SafeDllSearchMode", 0, REG_DWORD, (LPBYTE) ®val, sizeof(DWORD) ) != ERROR_SUCCESS) printf("Error writing SafeDllSearchMode. Error: %u\n", (UINT) GetLastError()); RegCloseKey(hkey); } else printf("Error opening Session Manager key for writing. Error: %u\n", (UINT) GetLastError()); } else printf("SafeDllSearchMode is set to 0\n"); }/*end else*/ } return TRUE; }
Synchronizer::Synchronizer(const WCHAR* syncfilepath) : indexDiscarded(true), syncfilepath(str::Dup(syncfilepath)) { _wstat(syncfilepath, &syncfileTimestamp); }
static bool path_stat(const char *path, enum stat_mode mode, int32_t *size) { #if defined(VITA) || defined(PSP) SceIoStat buf; char *tmp = strdup(path); size_t len = strlen(tmp); if (tmp[len-1] == '/') tmp[len-1]='\0'; if (sceIoGetstat(tmp, &buf) < 0) { free(tmp); return false; } free(tmp); #elif defined(__CELLOS_LV2__) CellFsStat buf; if (cellFsStat(path, &buf) < 0) return false; #elif defined(_WIN32) struct _stat buf; char *path_local; wchar_t *path_wide; DWORD file_info; if (!path || !*path) return false; (void)path_wide; (void)path_local; (void)file_info; #if defined(LEGACY_WIN32) path_local = utf8_to_local_string_alloc(path); file_info = GetFileAttributes(path_local); _stat(path_local, &buf); if (path_local) free(path_local); #else path_wide = utf8_to_utf16_string_alloc(path); file_info = GetFileAttributesW(path_wide); _wstat(path_wide, &buf); if (path_wide) free(path_wide); #endif if (file_info == INVALID_FILE_ATTRIBUTES) return false; #else struct stat buf; if (stat(path, &buf) < 0) return false; #endif if (size) *size = (int32_t)buf.st_size; switch (mode) { case IS_DIRECTORY: #if defined(VITA) || defined(PSP) return FIO_S_ISDIR(buf.st_mode); #elif defined(__CELLOS_LV2__) return ((buf.st_mode & S_IFMT) == S_IFDIR); #elif defined(_WIN32) return (file_info & FILE_ATTRIBUTE_DIRECTORY); #else return S_ISDIR(buf.st_mode); #endif case IS_CHARACTER_SPECIAL: #if defined(VITA) || defined(PSP) || defined(__CELLOS_LV2__) || defined(_WIN32) return false; #else return S_ISCHR(buf.st_mode); #endif case IS_VALID: return true; } return false; }
//-------------------------------------------------------------- // move current working directory up tree until file is found void mgOSFindWD( const char* fileName) { WCHAR* oldCWD = _wgetcwd(NULL, 0); if (oldCWD == NULL) throw new mgException("unable to get _getcwd"); mgString cwd(oldCWD); //mgDebug("CWD is %s", (const char*) cwd); BOOL changed = false; while (true) { mgString name; if (cwd.endsWith("\\")) name.format("%s%s", (const char*) cwd, fileName); else name.format("%s\\%s", (const char*) cwd, fileName); WCHAR* wideName; int wideLen; name.toWCHAR(wideName, wideLen); struct _stat filestat; BOOL found = 0 == _wstat(wideName, &filestat); delete wideName; wideName = NULL; if (found) { // mgDebug("found %s", (const char*) name); break; } else { // remove last directory from cwd int slash = cwd.reverseFind(cwd.length(), '\\'); if (slash != -1) { cwd.deleteAt(slash, cwd.length()-slash); changed = true; } else { // no more directories. file not found. mgString start(oldCWD); throw new mgException("mgOSFindWD cannot find %s from %s", (const char*) fileName, (const char*) start); } } } // set the new working directory if (changed) { // move errors.txt to new location WCHAR* wideOld; int lenOld; mgString oldErrors(oldCWD); oldErrors += "\\errors.txt"; oldErrors.toWCHAR(wideOld, lenOld); mgString newErrors(cwd); newErrors += "\\errors.txt"; WCHAR* wideNew; int lenNew; newErrors.toWCHAR(wideNew, lenNew); MoveFileEx(wideOld, wideNew, MOVEFILE_REPLACE_EXISTING); delete wideOld; wideOld = NULL; delete wideNew; wideNew = NULL; if (0 != _chdir(cwd)) throw new mgException("unable to _chdir(%s)", (const char*) cwd); } free(oldCWD); oldCWD = NULL; }
/* Wrapper for Windows stat function, which provides st_dev and st_ino. These are calculated as follows: st_dev is set to the drive number (0=A 1=B ...). Our virtual root "/" gets a st_dev of 0xff. st_ino is hashed from the full file path. Each half produces a 32 bit hash. These are concatenated to a 64 bit value. The risk that st_ino is the same for two files on the system is, if I'm not mistaken, b=pigeon(2**32, f)**2. For f=1000, b=1e-08. By using a 64 bit hash function this risk can be lowered. Possible future enhancement. pigeon() can be calculated in Python with: def pigeon(m, n): res = 1.0 for i in range(m - n + 1, m): res = res * i / m return 1 - res */ int win_stat(const char *file_name, backend_statstruct * buf) { wchar_t *winpath; int ret; wchar_t pathbuf[4096]; int retval; size_t namelen; wchar_t *splitpoint; char savedchar; struct _stat win_statbuf; /* Special case: Our top-level virtual root, containing each drive represented as a directory. Compare with "My Computer" etc. This virtual root has a hardcoded hash value of 1, to simplify debugging etc. */ if (!strcmp(file_name, "/")) { buf->st_mode = S_IFDIR | S_IRUSR | S_IWUSR; buf->st_nlink = MAX_NUM_DRIVES + 3; /* 3 extra for: . .. / */ buf->st_uid = 1; buf->st_gid = 1; buf->st_rdev = 0; buf->st_size = 4096; buf->st_atime = 0; buf->st_mtime = 0; buf->st_ctime = 0; buf->st_dev = 0xff; buf->st_ino = 1; return 0; } winpath = intpath2winpath(file_name); if (!winpath) { errno = EINVAL; return -1; } ret = _wstat(winpath, &win_statbuf); if (ret < 0) { free(winpath); return ret; } /* Copy values to our struct */ buf->st_mode = win_statbuf.st_mode; buf->st_nlink = win_statbuf.st_nlink; buf->st_uid = win_statbuf.st_uid; buf->st_gid = win_statbuf.st_gid; buf->st_rdev = win_statbuf.st_rdev; buf->st_size = win_statbuf.st_size; buf->st_atime = win_statbuf.st_atime; buf->st_mtime = win_statbuf.st_mtime; buf->st_ctime = win_statbuf.st_ctime; buf->st_blocks = win_statbuf.st_size / 512; retval = GetFullPathNameW(winpath, wsizeof(pathbuf), pathbuf, NULL); if (!retval) { errno = ENOENT; return -1; } /* Set st_dev to the drive number */ buf->st_dev = tolower(pathbuf[0]) - 'a'; /* GetLongPathName fails if called with only x:\, and drive x is not ready. So, only call it for other paths. */ if (pathbuf[0] && wcscmp(pathbuf + 1, L":\\")) { retval = GetLongPathNameW(pathbuf, pathbuf, wsizeof(pathbuf)); if (!retval || (unsigned) retval > wsizeof(pathbuf)) { /* Strangely enough, GetLongPathName returns ERROR_SHARING_VIOLATION for locked files, such as hiberfil.sys */ if (GetLastError() != ERROR_SHARING_VIOLATION) { errno = ENAMETOOLONG; return -1; } } } /* Hash st_ino, by splitting in two halves */ namelen = wcslen(pathbuf); splitpoint = &pathbuf[namelen / 2]; savedchar = *splitpoint; *splitpoint = '\0'; buf->st_ino = wfnv1a_32(pathbuf, 0); assert(sizeof(buf->st_ino) == 8); buf->st_ino = buf->st_ino << 32; *splitpoint = savedchar; buf->st_ino |= wfnv1a_32(splitpoint, 0); #if 0 fprintf(stderr, "win_stat: file=%s, ret=%d, st_dev=0x%x, st_ino=0x%I64x\n", file_name, ret, buf->st_dev, buf->st_ino); #endif free(winpath); return ret; }
/* * Arguments: path (string), [more_info (boolean)] * Returns: [is_directory (boolean), is_file (boolean), * is_read (boolean), is_write (boolean), is_execute (boolean), * [is_link (boolean), size (number), * access_time (number), modify_time (number), create_time (number)]] */ static int sys_stat (lua_State *L) { const char *path = luaL_checkstring(L, 1); const int more_info = lua_toboolean(L, 2); #ifndef _WIN32 struct stat st; #else struct _stat st; #endif int res; sys_vm_leave(L); #ifndef _WIN32 res = stat(path, &st); #else { void *os_path = utf8_to_filename(path); if (!os_path) return sys_seterror(L, ERROR_NOT_ENOUGH_MEMORY); res = is_WinNT ? _wstat(os_path, &st) : _stat(os_path, &st); free(os_path); } #endif sys_vm_enter(L); if (!res) { /* is directory? */ lua_pushboolean(L, #ifndef _WIN32 S_ISDIR(st.st_mode) #else st.st_mode & _S_IFDIR #endif ); /* is regular file? */ lua_pushboolean(L, #ifndef _WIN32 S_ISREG(st.st_mode) #else st.st_mode & _S_IFREG #endif ); /* can anyone read from file? */ lua_pushboolean(L, #ifndef _WIN32 st.st_mode & (S_IRUSR | S_IRGRP | S_IROTH) #else st.st_mode & _S_IREAD #endif ); /* can anyone write to file? */ lua_pushboolean(L, #ifndef _WIN32 st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH) #else st.st_mode & _S_IWRITE #endif ); /* can anyone execute the file? */ lua_pushboolean(L, #ifndef _WIN32 st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH) #else st.st_mode & _S_IEXEC #endif ); if (more_info) { /* is link? */ #ifndef _WIN32 lua_pushboolean(L, S_ISLNK(st.st_mode)); #else DWORD attr; { void *os_path = utf8_to_filename(path); if (!os_path) return sys_seterror(L, ERROR_NOT_ENOUGH_MEMORY); attr = is_WinNT ? GetFileAttributesW(os_path) : GetFileAttributesA(os_path); free(os_path); } lua_pushboolean(L, attr > 0 && (attr & FILE_ATTRIBUTE_REPARSE_POINT)); #endif lua_pushnumber(L, (lua_Number) st.st_size); /* size in bytes */ lua_pushnumber(L, (lua_Number) st.st_atime); /* access time */ lua_pushnumber(L, (lua_Number) st.st_mtime); /* modification time */ lua_pushnumber(L, (lua_Number) st.st_ctime); /* creation time */ return 10; } return 5; } return sys_seterror(L, 0); }
_zip_mkstemp(char *path) #endif { #ifndef _WIN32 int fd; #endif #ifdef UNICODE wchar_t *start, *trv; struct _stat sbuf; #else char *start, *trv; struct stat sbuf; #endif pid_t pid; /* To guarantee multiple calls generate unique names even if the file is not created. 676 different possibilities with 7 or more X's, 26 with 6 or less. */ // Urgh, not threadsafe at all. #ifdef UNICODE static wchar_t xtra[3] = L"aa"; #else static char xtra[3] = "aa"; #endif int xcnt = 0; pid = getpid(); /* Move to end of path and count trailing X's. */ for (trv = path; *trv; ++trv) if (*trv == 'X') xcnt++; else xcnt = 0; /* Use at least one from xtra. Use 2 if more than 6 X's. */ if (*(trv - 1) == 'X') *--trv = xtra[0]; if (xcnt > 6 && *(trv - 1) == 'X') *--trv = xtra[1]; /* Set remaining X's to pid digits with 0's to the left. */ while (*--trv == 'X') { *trv = (pid % 10) + '0'; pid /= 10; } /* update xtra for next call. */ if (xtra[0] != 'z') xtra[0]++; else { xtra[0] = 'a'; if (xtra[1] != 'z') xtra[1]++; else xtra[1] = 'a'; } /* * check the target directory; if you have six X's and it * doesn't exist this runs for a *very* long time. */ for (start = trv + 1;; --trv) { if (trv <= path) break; if (*trv == '/') { *trv = '\0'; #ifdef UNICODE if (_wstat(path, &sbuf)) #else if (stat(path, &sbuf)) #endif return (0); #ifndef _WIN32 if (!S_ISDIR(sbuf.st_mode)) { errno = ENOTDIR; return (0); } #endif *trv = '/'; break; } } #ifdef _WIN32 return 0; #else for (;;) { if ((fd=open(path, O_CREAT|O_EXCL|O_RDWR|O_BINARY, 0600)) >= 0) return (fd); if (errno != EEXIST) return (0); /* tricky little algorithm for backward compatibility */ for (trv = start;;) { if (!*trv) return (0); if (*trv == 'z') *trv++ = 'a'; else { if (isdigit((unsigned char)*trv)) *trv = 'a'; else ++*trv; break; } } } #endif /*NOTREACHED*/ }
int GetStat(const std::wstring& aFile, struct stat* s) { return _wstat(aFile.c_str(), reinterpret_cast<struct _stat*>(s)); }
BOOL MetaLauncher::createMenuItem(ULONG id, const char *path, size_t pathlen) { vnclog.Print(1, _T("%s: id=0x%X\n"), __FUNCTION__, id); wchar_t *p; // setup link path : m_baseMenuFolder + path (+ @desktopname) + ".lnk" size_t linkPathLen = wcslen(m_baseMenuFolder) + pathlen + wcslen(m_clientconn->m_desktopNameW) + 6; wchar_t *linkPath = new wchar_t[linkPathLen]; wcscpy(linkPath, m_baseMenuFolder); // append path with converting UTF-8 to UCS-2LE int pos = wcslen(linkPath); int wlen = MultiByteToWideChar(CP_UTF8, 0, path, (int)pathlen, &linkPath[pos], linkPathLen - pos); if (wlen <= 0) { vnclog.Print(0, _T("MultiByteToWideChar failed. (error %d)\n"), GetLastError()); delete[] linkPath; return FALSE; } linkPath[pos + wlen] = L'\0'; // convert '/' to '\\' while ((p = wcschr(linkPath, L'/')) != NULL) *p = L'\\'; // setup description text wchar_t *appName = wcsrchr(linkPath, '\\'); if (appName != NULL) appName++; // remove first '\\' else appName = linkPath; wchar_t *description = new wchar_t[wcslen(appName) + 1 + wcslen(m_clientconn->m_desktopNameW) + 1]; wcscpy(description, appName); wcscat(description, L"@"); wcscat(description, m_clientconn->m_desktopNameW); // add remote desktop name to linkpath if menu directory is not separated // XXX: maybe another option is needed if (m_clientconn->m_opts.m_menuLoc != MENULOC_SEPARATE) { wcscat(linkPath, L"@"); wcscat(linkPath, m_clientconn->m_desktopNameW); } wcscat(linkPath, L".lnk"); // add extension // check if linkPath already exists struct _stat st; if (_wstat(linkPath, &st) == 0) { vnclog.Print(0, _T("Failed to create identical link path (id=0x%X).\n"), id); delete[] description; delete[] linkPath; return FALSE; } // create sub directories createMenuDirs(linkPath); // remember link path if (m_fpMenuList) { fputws(linkPath, m_fpMenuList); fputws(L"\n", m_fpMenuList); } // setup target command arguments wchar_t targetArgs[30]; _snwprintf(targetArgs, 30, L"-launch %08X:%08X", m_clientconn->m_hwnd1, id); // setup icon path wchar_t *iconPath = createIconPath(id); // create shortcut HRESULT hr; IShellLinkW *pShellLink; IPersistFile *pPersistFile; CoInitialize(NULL); hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLinkW, (void**)&pShellLink); if (hr == S_OK) hr = pShellLink->SetPath(m_programName); if (hr == S_OK) hr = pShellLink->SetArguments(targetArgs); if (hr == S_OK) hr = pShellLink->SetIconLocation(iconPath, 0); if (hr == S_OK) hr = pShellLink->SetDescription(description); if (hr == S_OK) hr = pShellLink->QueryInterface(IID_IPersistFile, (void **)&pPersistFile); if (hr == S_OK) hr = pPersistFile->Save(linkPath, TRUE); // clean up pPersistFile->Release(); pShellLink->Release(); CoUninitialize(); delete[] iconPath; delete[] description; delete[] linkPath; return (hr == S_OK); }
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; }
void RemoteBitmap::LoadImage(BSTR fileName) { struct _stat sbuf; AtlTrace("image filename=%s\n", (char*)_bstr_t(fileName)); if (::wcscspn(fileName, L"http://") == 0) { // Disconnect us from any existing thread { SysStatsUtils::Lock lock(cs); if (loadThread) { if (::wcscmp(fileName, loadThread->bstrURL) == 0) { AtlTrace("Gawd. Give us a chance guv\n"); return; } AtlTrace("Cutting existing thread free\n"); loadThread->bmp = NULL; } } if (cs) cs->RemoveRef(); cs = new CSRef(); cs->AddRef(); SysStatsUtils::Lock lock(cs); loadThread = new BitmapHTTPSink(this, fileName, cs); } else { if (bmp) delete bmp; bmp = 0; if (_wstat(fileName, &sbuf) == 0) { if (wcsstr(fileName, L".ico") == NULL) { bmp = Bitmap::FromFile(fileName); } else { HICON icon = (HICON) ::LoadImage(0,_bstr_t(fileName),IMAGE_ICON,128,128,LR_LOADFROMFILE); ICONINFO iconInfo = {0}; iconInfo.fIcon = TRUE; GetIconInfo(icon,&iconInfo); BitmapData data; bmp = new Bitmap(iconInfo.xHotspot*2,iconInfo.yHotspot*2); Rect r(0,0,bmp->GetWidth(),bmp->GetHeight()); bmp->LockBits(&r,ImageLockModeWrite,PixelFormat32bppARGB,&data); GetBitmapBits(iconInfo.hbmColor,iconInfo.xHotspot*iconInfo.yHotspot*4*4,data.Scan0); bmp->UnlockBits(&data); DeleteObject(iconInfo.hbmColor); DeleteObject(iconInfo.hbmMask); DestroyIcon(icon); } } } }
static bool statFile(String path, struct _stat& st) { ASSERT_ARG(path, !path.isNull()); return !_wstat(path.charactersWithNullTermination(), &st) && (st.st_mode & _S_IFMT) == _S_IFREG; }
//----------------------------------------------------------------------- Ogre::DataStreamPtr UnicodeFileSystemArchive::open(const String& _filename, bool _readOnly) const { WString wfullpath = getFullPath(_filename); // Use filesystem to determine size // (quicker than streaming to the end and back) struct _stat tagStat; int ret = _wstat(wfullpath.c_str(), &tagStat); if(ret != 0) { GOTHOGRE_EXCEPT(_filename << " - Problem getting file size" << " (archive " << getName() << ")."); } // Always open in binary mode // Also, always include reading std::ios::openmode mode = std::ios::in | std::ios::binary; std::istream* baseStream = 0; std::ifstream* roStream = 0; std::fstream* rwStream = 0; if (_readOnly) { roStream = OGRE_NEW_T(std::ifstream, MEMCATEGORY_GENERAL)(); roStream->open(wfullpath.c_str(), mode); baseStream = roStream; } else { if (isReadOnly()) { GOTHOGRE_EXCEPT(_filename << " - Cannot open a file for writing in" << " read-only archive " << getName() << "."); } mode |= std::ios::out; rwStream = OGRE_NEW_T(std::fstream, MEMCATEGORY_GENERAL)(); rwStream->open(wfullpath.c_str(), mode); baseStream = rwStream; } // Should check ensure open succeeded, in case fail for some reason. if (baseStream->fail()) { OGRE_DELETE_T(roStream, basic_ifstream, MEMCATEGORY_GENERAL); OGRE_DELETE_T(rwStream, basic_fstream, MEMCATEGORY_GENERAL); GOTHOGRE_EXCEPT(_filename << " - Cannot open file in" << " archive " << getName() << "."); } GOTHOGRE_INFO(_filename << " - " << (_readOnly ? "Loading from" : "Saving to") << " archive " << getName() << "."); /// Construct return stream, tell it to delete on destroy FileStreamDataStream* stream = 0; if (rwStream) { // use the writeable stream stream = OGRE_NEW FileStreamDataStream(_filename, rwStream, tagStat.st_size, true); } else { // read-only stream stream = OGRE_NEW FileStreamDataStream(_filename, roStream, tagStat.st_size, true); } return DataStreamPtr(stream); }
static Time get_modified(const String& file_path) { struct _stat buf; return _wstat(file_path.c_str(), &buf) ? 0 : buf.st_mtime; }
Error FileAccessWindows::_open(const String &p_path, int p_mode_flags) { path_src = p_path; path = fix_path(p_path); if (f) close(); const wchar_t *mode_string; if (p_mode_flags == READ) mode_string = L"rb"; else if (p_mode_flags == WRITE) mode_string = L"wb"; else if (p_mode_flags == READ_WRITE) mode_string = L"rb+"; else if (p_mode_flags == WRITE_READ) mode_string = L"wb+"; else return ERR_INVALID_PARAMETER; /* pretty much every implementation that uses fopen as primary backend supports utf8 encoding */ struct _stat st; if (_wstat(path.c_str(), &st) == 0) { if (!S_ISREG(st.st_mode)) return ERR_FILE_CANT_OPEN; }; #ifdef TOOLS_ENABLED // Windows is case insensitive, but all other platforms are sensitive to it // To ease cross-platform development, we issue a warning if users try to access // a file using the wrong case (which *works* on Windows, but won't on other // platforms). if (p_mode_flags == READ) { WIN32_FIND_DATAW d = { 0 }; HANDLE f = FindFirstFileW(path.c_str(), &d); if (f) { String fname = d.cFileName; if (fname != String()) { String base_file = path.get_file(); if (base_file != fname && base_file.findn(fname) == 0) { WARN_PRINTS("Case mismatch opening requested file '" + base_file + "', stored as '" + fname + "' in the filesystem. This file will not open when exported to other case-sensitive platforms."); } } FindClose(f); } } #endif if (is_backup_save_enabled() && p_mode_flags & WRITE && !(p_mode_flags & READ)) { save_path = path; path = path + ".tmp"; } _wfopen_s(&f, path.c_str(), mode_string); if (f == NULL) { last_error = ERR_FILE_CANT_OPEN; return ERR_FILE_CANT_OPEN; } else { last_error = OK; flags = p_mode_flags; return OK; } }
//PRIVATE: Return the name of to file to write into void CLog::getFilename(std::wstring &filename) { //Test if the directory exist std::wstring directory; #ifdef WIN32 DWORD dwError=0; directory=m_directory + L"\\"; DWORD dwAttr = GetFileAttributes(directory.c_str()); if(dwAttr == INVALID_FILE_ATTRIBUTES) dwError = GetLastError(); if(dwError == ERROR_FILE_NOT_FOUND || dwError == ERROR_PATH_NOT_FOUND) { m_directory=L"."; directory=m_directory + L"\\"; } #else // --> TODO : Test if the directory exist directory = m_directory; struct stat buffer; if ( stat(utilStringNarrow(directory).c_str(),&buffer)){ // check error code m_directory=LOG_DIRECTORY_DEFAULT; } directory=m_directory + L"/"; #endif //Initialize the root filename std::wstring root_filename; root_filename=directory + m_prefix + L"_"; if(m_groupinnewfile && m_group.size()>0) root_filename+=m_group + L"_"; wchar_t index[5]; swprintf_s(index,5,L"%d",0); //If there is a maximal file size, // we parse the file from index 0 to m_filenr-1 // until we find one -that doesn't exist // or // -with a size smaller than m_filesize // If we don't, we have to rename the files // //Else If there is only one file its index is 0 if(m_filesize>0) { //There must be at least 2 files if(m_filenr<2) m_filenr=2; std::wstring file; #ifdef WIN32 struct _stat results; #else struct stat results; #endif bool find=false; for(int i=0;i<m_filenr;i++) { swprintf_s(index,5,L"%d",i); file=root_filename + index + L".log"; #ifdef WIN32 if (_wstat(file.c_str(), &results) != 0 || results.st_size<m_filesize) #else if (stat(utilStringNarrow(file).c_str(), &results) != 0 || results.st_size<m_filesize) #endif { find=true; break; } } if(!find) { renameFiles(root_filename.c_str()); swprintf_s(index,5,L"%d",m_filenr-1); } } filename=root_filename + index + L".log"; }
/** * Returns the root path of java's home directory. * * @param rootPath returned value: pointer to unicode buffer, allocated * by the VM, to be filled with the root path. * @param rootPathLen IN : lenght of max rootPath buffer * OUT : lenght of set rootPath * @return <tt>JAVACALL_OK</tt> if operation completed successfully * <tt>JAVACALL_FAIL</tt> if an error occured */ javacall_result javacall_dir_get_root_path(javacall_utf16* /* OUT */ rootPath, int* /*IN | OUT*/ rootPathLen) { wchar_t dirBuffer[JAVACALL_MAX_ROOT_PATH_LENGTH + 1]; wchar_t currDir[JAVACALL_MAX_ROOT_PATH_LENGTH + 1]; wchar_t* midpHome; if (rootPath == NULL || rootPathLen == NULL) { return JAVACALL_FAIL; } /* * If MIDP_HOME is set, just use it. Does not check if MIDP_HOME is * pointing to a directory contain "appdb". */ midpHome = _wgetenv(L"MIDP_HOME"); if (midpHome != NULL) { int len = (int) wcslen(midpHome); if (len >= *rootPathLen) { * rootPathLen = 0; javacall_print("javacall_dir_get_root_path: MIDP_HOME " "is too long."); return JAVACALL_FAIL; } wcscpy(rootPath, midpHome); * rootPathLen = len; return JAVACALL_OK; } /* * Look for "appdb" until it is found in the following places: * - current directory; * - the parent directory of the midp executable; * - the grandparent directory of the midp executable. */ if ( _wgetcwd( currDir, sizeof(currDir)/sizeof(wchar_t) ) == NULL) { * rootPathLen = 0; javacall_print("javacall_dir_get_root_path: _wgetcwd failed"); return JAVACALL_FAIL; } else { wchar_t* lastsep; struct _stat statbuf; int i, j = 1; wchar_t chSep = javacall_get_file_separator(); wchar_t filesep[2] = {chSep, (wchar_t)0}; dirBuffer[sizeof(dirBuffer)/sizeof(wchar_t) - 1] = (wchar_t)0; wcsncpy(dirBuffer, currDir, sizeof(dirBuffer)/sizeof(wchar_t) - 1); while (j < 2) { /* Look for the last slash in the pathname. */ lastsep = wcsrchr(dirBuffer, *filesep); if (lastsep != NULL) { *(lastsep + 1) = (wchar_t)'\0'; } else { /* no file separator */ wcscpy(dirBuffer, L"."); wcscat(dirBuffer, filesep); } wcscat(dirBuffer, L"appdb"); i = 0; /* try to search for "appdb" 3 times only (see above) */ while (i < 3) { memset(&statbuf, 0, sizeof(statbuf)); /* found it and it is a directory */ if ((_wstat(dirBuffer, &statbuf) == 0) && (statbuf.st_mode & S_IFDIR)) { break; } /* strip off "appdb" to add 1 more level of ".." */ *(wcsrchr(dirBuffer, *filesep)) = (wchar_t)'\0'; wcscat(dirBuffer, filesep); wcscat(dirBuffer, L".."); wcscat(dirBuffer, filesep); wcscat(dirBuffer, L"appdb"); i++; } /* end while (i < 3) */ if (i < 3) { break; } j++; } /* end while (j < 2) */ if (j == 2) { javacall_print("Warning: cannot find appdb subdirectory.\n" "Please specify MIDP_HOME environment variable such " "that $MIDP_HOME\\lib contains the proper configuration " "files.\n"); return JAVACALL_FAIL; } /* strip off "appdb" from the path */ *(wcsrchr(dirBuffer, *filesep)) = (wchar_t)'\0'; wcscpy(rootPath, dirBuffer); * rootPathLen = wcslen(rootPath); return JAVACALL_OK; } }
int Synchronizer::RebuildIndex() { indexDiscarded = false; // save sync file timestamp _wstat(syncfilepath, &syncfileTimestamp); return PDFSYNCERR_SUCCESS; }