BasicIo::AutoPtr FileIo::temporary() const { BasicIo::AutoPtr basicIo; Impl::StructStat buf; int ret = p_->stat(buf); #if defined WIN32 && !defined __CYGWIN__ DWORD nlink = p_->winNumberOfLinks(); #else nlink_t nlink = buf.st_nlink; #endif // If file is > 1MB and doesn't have hard links then use a file, otherwise // use a memory buffer. I.e., files with hard links always use a memory // buffer, which is a workaround to ensure that the links don't get broken. if (ret != 0 || (buf.st_size > 1048576 && nlink == 1)) { pid_t pid = ::getpid(); std::auto_ptr<FileIo> fileIo; #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { std::wstring tmpname = wpath() + s2ws(toString(pid)); fileIo = std::auto_ptr<FileIo>(new FileIo(tmpname)); } else #endif { std::string tmpname = path() + toString(pid); fileIo = std::auto_ptr<FileIo>(new FileIo(tmpname)); } if (fileIo->open("w+b") != 0) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(10, wpath(), "w+b", strError().c_str()); } else #endif { throw Error(10, path(), "w+b", strError()); } } fileIo->p_->copyXattrFrom(*this); basicIo = fileIo; } else { basicIo.reset(new MemIo); } return basicIo; }
void Path::remove(const std::string & path) { NTA_CHECK(!path.empty()) << "Can't remove an empty path"; // Just return if it doesn't exist already if (!Path::exists(path)) return; if (isDirectory(path)) { Directory::removeTree(path); return; } #ifdef WIN32 std::wstring wpath(utf8ToUnicode(path)); BOOL res = ::DeleteFile(/*(LPCTSTR)*/wpath.c_str()); if (res == FALSE) NTA_THROW << "Path::remove() -- unable to delete '" << path << "' error message: " << OS::getErrorMessage(); #else int res = ::remove(path.c_str()); if (res != 0) NTA_THROW << "Path::remove() -- unable to delete '" << path << "' error message: " << OS::getErrorMessage(); #endif }
void McfViewerForm::loadMcf(const char* path) { m_pHandle = McfHandle(); m_pHandle->setFile(path); m_pHandle->parseMCF(); MCFCore::MCFHeaderI* temp = m_pHandle->getHeader(); m_labId->SetLabel(gcWString(L"{0}", temp->getId())); m_labVersion->SetLabel(gcWString(L"{0}", temp->getFileVer())); m_labType->SetLabel(gcWString(L"{0}", temp->getType())); m_labMCFVers->SetLabel(gcWString(L"{0}", temp->getBuild().operator size_t())); m_labPatch->SetLabel(gcWString(L"{0}", temp->getFlags())); m_labBranch->SetLabel(gcWString(L"{0}", temp->getBranch().operator size_t())); //m_pHandle->Par uint32 count = m_pHandle->getFileCount(); const char* mcfPath = m_pHandle->getFile(); m_tcFileTree->DeleteAllItems(); wxTreeItemId root = m_tcFileTree->AddRoot(UTIL::FS::PathWithFile(mcfPath).getFolderPath()); m_tcFileTree->SetItemTextColour(root, *wxBLACK); for (uint32 x=0; x<count; x++) { MCFCore::MCFFileI* m_pHandleFile = m_pHandle->getMCFFile(x); if (!m_pHandleFile) continue; const char* path = m_pHandleFile->getPath(); wxTreeItemId node = root; if (path && strcmp(path,"")!=0 && strcmp(path, "\\") !=0) { wxTreeItemId lastNode; wxTreeItemId item; gcString path(m_pHandleFile->getPath()); gcWString wpath(path); node = recCreateNodes(wpath.c_str(), wpath.size(), root); } wxTreeItemId item = m_tcFileTree->AppendItem(node, m_pHandleFile->getName()); if (!m_pHandleFile->isSaved()) m_tcFileTree->SetItemTextColour(item, *wxRED); else m_tcFileTree->SetItemTextColour(item, *wxBLACK); // AddRoot } m_tcFileTree->Toggle(root); }
bool ase_file_exists(const ase_string& fname) { ase_utf16_string wpath(fname); WIN32_FIND_DATAW fdata; auto_dir d(FindFirstFileW(wpath.data(), &fdata)); return (d.get() != INVALID_HANDLE_VALUE); }
bool IsRelative(const std::string& path) { #ifdef US_PLATFORM_WINDOWS if (path.size() > MAX_PATH) return false; std::wstring wpath(ToWString(path)); return (TRUE == ::PathIsRelativeW(wpath.c_str()))? true:false; #else return path.empty() || path[0] != DIR_SEP; #endif }
wpath bit::torrent::files_proxy::file_proxy::name() const { try { return t_.ptr->files()[n_].completed_name(); } HAL_GENERIC_PIMPL_EXCEPTION_CATCH("bit::torrent::files_proxy::file_proxy::get_name()") return wpath(); }
//------------------------------------------------------------------------------ int get_file_size(const char* path) { wstr<280> wpath(path); void* handle = CreateFile(path, 0, 0, nullptr, OPEN_EXISTING, 0, nullptr); if (handle == INVALID_HANDLE_VALUE) return -1; int ret = GetFileSize(handle, nullptr); // 2Gb max I suppose... CloseHandle(handle); return ret; }
static int CALLBACK BrowserWindowCallbackProc(HWND hwnd, UINT msg, LPARAM lparam, LPARAM lpdata) { if(msg == BFFM_INITIALIZED) { if(lpdata) { auto state = (BrowserWindow::State*)lpdata; utf16_t wpath(string{state->path}.transform("/", "\\")); if(state->title) SetWindowText(hwnd, utf16_t(state->title)); SendMessage(hwnd, BFFM_SETSELECTION, TRUE, (LPARAM)(wchar_t*)wpath); } } return 0; }
WeaselIME::WeaselIME(HIMC hIMC) : m_hIMC(hIMC) , m_composing(false) , m_preferCandidatePos(false) { WCHAR path[MAX_PATH]; GetModuleFileName(NULL, path, _countof(path)); wstring exe = wpath(path).filename(); if (boost::iequals(L"chrome.exe", exe)) m_preferCandidatePos = true; }
//------------------------------------------------------------------------------ int get_path_type(const char* path) { wstr<280> wpath(path); DWORD attr = GetFileAttributesW(wpath.c_str()); if (attr == ~0) return path_type_invalid; if (attr & FILE_ATTRIBUTE_DIRECTORY) return path_type_dir; return path_type_file; }
HANDLE FindFirstFileU8(const char *path, WIN32_FIND_DATA_U8 *fdat) { Wstr wpath(path); WIN32_FIND_DATAW fdat_w; HANDLE ret; if ((ret = ::FindFirstFileW(wpath.s(), &fdat_w)) != INVALID_HANDLE_VALUE) { WIN32_FIND_DATA_WtoU8(&fdat_w, fdat); } return ret; }
void Path::setPermissions(const std::string &path, bool userRead, bool userWrite, bool groupRead, bool groupWrite, bool otherRead, bool otherWrite ) { if(Path::isDirectory(path)) { Directory::Iterator iter(path); Directory::Entry e; while(iter.next(e)) { std::string sub = Path::join(path, e.path); setPermissions(sub, userRead, userWrite, groupRead, groupWrite, otherRead, otherWrite); } } #if WIN32 int countFailure = 0; std::wstring wpath(utf8ToUnicode(path)); DWORD attr = GetFileAttributes(wpath.c_str()); if(attr != INVALID_FILE_ATTRIBUTES) { if(userWrite) attr &= ~FILE_ATTRIBUTE_READONLY; BOOL res = SetFileAttributes(wpath.c_str(), attr); if(!res) { NTA_WARN << "Path::setPermissions: Failed to set attributes for " << path; ++countFailure; } } else { NTA_WARN << "Path::setPermissions: Failed to get attributes for " << path; ++countFailure; } if(countFailure > 0) { NTA_THROW << "Path::setPermissions failed for " << path; } #else mode_t mode = 0; if (userRead) mode |= S_IRUSR; if (userWrite) mode |= S_IRUSR; if (groupRead) mode |= S_IRGRP; if (groupWrite) mode |= S_IWGRP; if (otherRead) mode |= S_IROTH; if (otherWrite) mode |= S_IWOTH; chmod(path.c_str(), mode); #endif }
static string BrowserWindow_fileDialog(bool save, BrowserWindow::State& state) { string path = string{state.path}.replace("/", "\\"); string filters; for(auto& filter : state.filters) { lstring part = filter.split("("); if(part.size() != 2) continue; part[1].rtrim<1>(")"); part[1].replace(" ", ""); part[1].transform(",", ";"); filters.append(filter, "\t", part[1], "\t"); } utf16_t wfilters(filters); wchar_t wname[PATH_MAX + 1] = L""; utf16_t wpath(path); utf16_t wtitle(state.title); wchar_t* p = wfilters; while(*p != L'\0') { if(*p == L'\t') *p = L'\0'; p++; } if(path.empty() == false) { //clear COMDLG32 MRU (most recently used) file list //this is required in order for lpstrInitialDir to be honored in Windows 7 and above registry::remove("HKCU/Software/Microsoft/Windows/CurrentVersion/Explorer/ComDlg32/LastVisitedPidlMRU/"); registry::remove("HKCU/Software/Microsoft/Windows/CurrentVersion/Explorer/ComDlg32/OpenSavePidlMRU/"); } OPENFILENAME ofn; memset(&ofn, 0, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = state.parent ? state.parent->p.hwnd : 0; ofn.lpstrFilter = wfilters; ofn.lpstrInitialDir = wpath; ofn.lpstrFile = wname; ofn.lpstrTitle = wtitle; ofn.nMaxFile = PATH_MAX; ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; ofn.lpstrDefExt = L""; bool result = (save == false ? GetOpenFileName(&ofn) : GetSaveFileName(&ofn)); if(result == false) return ""; string name = (const char*)utf8_t(wname); name.transform("\\", "/"); return name; }
DWORD GetFullPathNameU8(const char *path, DWORD size, char *buf, char **fname) { Wstr wpath(path), wbuf(size); WCHAR *wfname=NULL; DWORD ret = ::GetFullPathNameW(wpath, size, wbuf.Buf(), &wfname); if (ret == 0 || ret > size) return ret; int fname_len = wfname ? WtoU8(wfname, buf, size) : 0; int path_len = WtoU8(wbuf, buf, size); *fname = wfname ? (buf + path_len - fname_len) : NULL; return ret; }
int FileIo::open(const std::string& mode) { close(); p_->openMode_ = mode; p_->opMode_ = Impl::opSeek; #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { p_->fp_ = ::_wfopen(wpath().c_str(), s2ws(mode).c_str()); } else #endif { p_->fp_ = ::fopen(path().c_str(), mode.c_str()); } if (!p_->fp_) return 1; return 0; }
bool Editor::tryClose(char const* path, wchar_t const* title) { if (modified()) { WideString wpath(path); switch (MessageBox(hWnd, WideString::format(L"Do you want to save changes to %s?", title), L"iLua Core", MB_YESNOCANCEL)) { case IDYES: save(wpath); case IDNO: return true; case IDCANCEL: return false; } } return true; }
BOOL LogMng::InitLogDb(BOOL with_import) { char path[MAX_PATH_U8]; if (!LogToDbName(logFile, path, isAlt)) { return FALSE; } Wstr wpath(path); BOOL db_exists = ::GetFileAttributesW(wpath.s()) != 0xffffffff; logDb = new LogDb(cfg); logDb->Init(wpath.s()); if (!db_exists && with_import) { AddTextLogToDb(cfg, logDb, logFile); } return TRUE; }
bool FileUtils::removeFile(const std::string &path) { // Remove downloaded file #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) std::wstring wpath(path.begin(), path.end()); if (DeleteFile(wpath.c_str())) { return true; } return false; #elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) std::string command = "cmd /c del /q "; std::string win32path = path; int len = win32path.length(); for (int i = 0; i < len; ++i) { if (win32path[i] == '/') { win32path[i] = '\\'; } } command += win32path; if (WinExec(command.c_str(), SW_HIDE) > 31) return true; else return false; #else std::string command = "rm -f "; // Path may include space. command += "\"" + path + "\""; if (system(command.c_str()) >= 0) return true; else return false; #endif }
std::string Path::getExecutablePath() { std::string epath = "UnknownExecutablePath"; #ifndef NTA_PLATFORM_win32 char *buf = new char[1000]; UInt32 bufsize = 1000; // sets bufsize to actual length. #if defined(NTA_PLATFORM_darwin86) || defined(NTA_PLATFORM_darwin64) _NSGetExecutablePath(buf, &bufsize); if (bufsize < 1000) buf[bufsize] = '\0'; #else int count = readlink("/proc/self/exe", buf, bufsize); if (count < 0) NTA_THROW << "Unable to read /proc/self/exe to get executable name"; if (count < 1000) buf[count] = '\0'; #endif // make sure it's null-terminated buf[999] = '\0'; epath = buf; delete[] buf; #else // windows wchar_t *buf = new wchar_t[1000]; GetModuleFileName(NULL, buf, 1000); // null-terminated string guaranteed unless length > 999 buf[999] = '\0'; std::wstring wpath(buf); delete[] buf; epath = unicodeToUtf8(wpath); #endif return epath; }
void DataBlock::writeToMem(std::string path) { int data_size = size; boost::iostreams::mapped_file_params param(path); param.flags = boost::iostreams::mapped_file::mapmode::readwrite; param.new_file_size = data_size; param.length = data_size; boost::iostreams::mapped_file_sink fout(param); if (!fout.is_open()) { throw fileError(std::string("Cannot write file: ") + path); } // push data to file readData((void*)fout.data(), data_size); fout.close(); // change permission // NOTE: here there might be a security issue need to be addressed boost::filesystem::wpath wpath(path); boost::filesystem::permissions(wpath, boost::filesystem::add_perms | boost::filesystem::group_read | boost::filesystem::others_read); }
bool FileUtils::createDirectory(const std::string& path) { CCASSERT(!path.empty(), "Invalid path"); if (isDirectoryExist(path)) return true; // Split the path size_t start = 0; size_t found = path.find_first_of("/\\", start); std::string subpath; std::vector<std::string> dirs; if (found != std::string::npos) { while (true) { subpath = path.substr(start, found - start + 1); if (!subpath.empty()) dirs.push_back(subpath); start = found+1; found = path.find_first_of("/\\", start); if (found == std::string::npos) { if (start < path.length()) { dirs.push_back(path.substr(start)); } break; } } } #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) WIN32_FILE_ATTRIBUTE_DATA wfad; std::wstring wpath(path.begin(), path.end()); if (!(GetFileAttributesEx(wpath.c_str(), GetFileExInfoStandard, &wfad))) { subpath = ""; for(unsigned int i = 0 ; i < dirs.size() ; ++i) { subpath += dirs[i]; if (i > 0 && !isDirectoryExist(subpath)) { std::wstring wsubpath(subpath.begin(), subpath.end()); BOOL ret = CreateDirectory(wsubpath.c_str(), NULL); if (!ret && ERROR_ALREADY_EXISTS != GetLastError()) { return false; } } } } return true; #elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) if ((GetFileAttributesA(path.c_str())) == INVALID_FILE_ATTRIBUTES) { subpath = ""; for (int i = 0; i < dirs.size(); ++i) { subpath += dirs[i]; if (!isDirectoryExist(subpath)) { BOOL ret = CreateDirectoryA(subpath.c_str(), NULL); if (!ret && ERROR_ALREADY_EXISTS != GetLastError()) { return false; } } } } return true; #else DIR *dir = NULL; // Create path recursively subpath = ""; for (int i = 0; i < dirs.size(); ++i) { subpath += dirs[i]; dir = opendir(subpath.c_str()); if (!dir) { // directory doesn't exist, should create a new one int ret = mkdir(subpath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); if (ret != 0 && (errno != EEXIST)) { // current directory can not be created, sub directories can not be created too // should return return false; } } else { // directory exists, should close opened dir closedir(dir); } } return true; #endif }
string fetchUrl(string server, string path) { BOOL bResults = FALSE; HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; string result; wstring wserver(server.begin(), server.end()); wstring wpath(path.begin(), path.end()); // Use WinHttpOpen to obtain a session handle. hSession = WinHttpOpen(L"Penis Browser/1.1", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); // Specify an HTTP server. if (hSession) hConnect = WinHttpConnect(hSession, wserver.c_str(), INTERNET_DEFAULT_HTTP_PORT, 0); // Create an HTTP request handle. if (hConnect) hRequest = WinHttpOpenRequest(hConnect, L"GET", wpath.c_str(), NULL, WINHTTP_NO_REFERER, NULL, NULL); // Send a request. if (hRequest) bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); // Keep checking for data until there is nothing left. if (bResults) { DWORD dwSize = 0; do { DWORD dwDownloaded = 0; LPSTR pszOutBuffer; // Check for available data. WinHttpQueryDataAvailable(hRequest, &dwSize); // Allocate space for the buffer. pszOutBuffer = new char[dwSize + 1]; // Read the Data. ZeroMemory(pszOutBuffer, dwSize + 1); if (WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded)) result.append(string(pszOutBuffer, dwDownloaded)); // Free the memory allocated to the buffer. delete[] pszOutBuffer; } while (dwSize > 0); } // Close any open handles. if (hRequest) WinHttpCloseHandle(hRequest); if (hConnect) WinHttpCloseHandle(hConnect); if (hSession) WinHttpCloseHandle(hSession); return result; }
bool ase_change_directory(const ase_string& dname) { ase_utf16_string wpath(dname); return (SetCurrentDirectoryW(wpath.data()) != 0); }
DWORD GetFileAttributesU8(const char *path) { Wstr wpath(path); return ::GetFileAttributesW(wpath.s()); }
BOOL SetFileAttributesU8(const char *path, DWORD attr) { Wstr wpath(path); return ::SetFileAttributesW(wpath.s(), attr); }
UINT GetDriveTypeU8(const char *path) { Wstr wpath(path); return ::GetDriveTypeW(wpath.s()); }
GLuint Ibex::ApplicationLauncher::createApplicationLauncherBitmap(std::vector<std::string> &paths, size_t &width, size_t &height, int &selectedX, int &selectedY,std::map<std::pair<int,int>,std::string> &applicationList) { const int iconRes = 96; const int iconSpacing = 8; int appCount = 0; for(int p = 0; p < paths.size(); ++p) { const char *path_ = paths[p].c_str(); std::vector<std::string> appDirectory = Filesystem::listDirectory(path_); for(int i = 0; i < appDirectory.size(); ++i) { if(appDirectory[i].find(".lnk") == std::string::npos && appDirectory[i].find(".exe") == std::string::npos) continue; ++appCount; } } const int vert = 8; const int horiz = ceil(float(appCount)/float(vert)); if(horiz == 0 || vert == 0) return 0; while(selectedX < 0) selectedX += (horiz > 0) ? horiz : 1; while(selectedY < 0) selectedY += vert; selectedX %= horiz; selectedY %= vert; width = horiz*(iconRes+2*iconSpacing); height = vert*(iconRes+2*iconSpacing); HDC hDC = GetDC(NULL); HDC hMemDC = CreateCompatibleDC(hDC); HBITMAP hMemBmp = CreateCompatibleBitmap(hDC, width, height); HGDIOBJ hOrgBMP = SelectObject(hMemDC, hMemBmp); // draw icons int count = 0; applicationList.clear(); for(int p = 0; p < paths.size(); ++p) { const char *path_ = paths[p].c_str(); std::vector<std::string> appDirectory; if(Filesystem::isDirectory(path_) && std::string(path_).find(".lnk") == std::string::npos && std::string(path_).find(".exe") == std::string::npos) { appDirectory = Filesystem::listDirectory(path_); } else { appDirectory.push_back(path_); std::cerr << path_ << std::endl; } for(int i = 0; i < appDirectory.size(); ++i) { if(appDirectory[i].find(".lnk") == std::string::npos && appDirectory[i].find(".exe") == std::string::npos) continue; const int x = (count/vert); const int y = (vert-(count%vert)-1); const int yApp = (count%vert); const std::string s(Filesystem::getFullPath(std::string(path_), appDirectory[i].c_str())); const char *path = s.c_str(); applicationList[std::pair<int,int>(x,yApp)] = s; // std::cerr << "***** ICON FOR: " << path << std::endl; std::wstring wpath(s.begin(), s.end()); std::cerr << wpath.c_str() << std::endl; SHFILEINFOW sfi = {0}; HRESULT hr = SHGetFileInfo(wpath.data(), -1,//attr, &sfi, sizeof(SHFILEINFO), SHGFI_ICON | /*SHGFI_SMALLICON | SHGFI_TYPENAME | */SHGFI_DISPLAYNAME);//SHGFI_USEFILEATTRIBUTES | SHGFI_ICON | SHGFI_TYPENAME); if(!SUCCEEDED(hr)) { continue; } // sfi.szDisplayName for name to display as text drawIconToDC(sfi.hIcon, hMemDC, x*(iconRes+2*iconSpacing)+0.5*iconSpacing, y*(iconRes+2*iconSpacing)+0.5*iconSpacing); ++count; } } // draw frame static HPEN hPen = CreatePen(PS_SOLID,5,RGB(255,0,0)); ::SelectObject(hMemDC, ::GetStockObject(NULL_BRUSH)); // transparent brush SelectObject(hMemDC, hPen); Rectangle(hMemDC, selectedX*(iconRes+2*iconSpacing), (vert-selectedY-1)*(iconRes+2*iconSpacing), selectedX*(iconRes+2*iconSpacing)+iconRes+2*iconSpacing, (vert-selectedY-1)*(iconRes+2*iconSpacing)+iconRes+2*iconSpacing); BITMAPINFOHEADER bi; bi.biSize = sizeof(BITMAPINFOHEADER); bi.biWidth = width; bi.biHeight = height; bi.biPlanes = 1; bi.biBitCount = 24; bi.biCompression = BI_RGB; bi.biSizeImage = 0; bi.biXPelsPerMeter = 0; bi.biYPelsPerMeter = 0; bi.biClrUsed = 0; bi.biClrImportant = 0; if(lpbitmap != 0) { delete [] lpbitmap; lpbitmap = 0; } if(lpbitmap == 0) { DWORD dwBmpSize = ((width * bi.biBitCount + 23) / 24) * 3 *height; lpbitmap = new char[dwBmpSize]; } // Gets the "bits" from the bitmap and copies them into a buffer // which is pointed to by lpbitmap. int result = GetDIBits(hMemDC, hMemBmp, 0, height, lpbitmap, (BITMAPINFO *)&bi, DIB_RGB_COLORS); if(appTexture == 0) { glGenTextures(1, &appTexture); } if(appTexture) { glBindTexture(GL_TEXTURE_2D, appTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, lpbitmap); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); } DeleteObject(hMemBmp); SelectObject(hMemDC, hOrgBMP); DeleteDC(hMemDC); ReleaseDC(NULL, hDC); return appTexture; }
//------------------------------------------------------------------------------ bool unlink(const char* path) { wstr<280> wpath(path); return (DeleteFileW(wpath.c_str()) == TRUE); }
byte* FileIo::mmap(bool isWriteable) { assert(p_->fp_ != 0); if (munmap() != 0) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), strError().c_str(), "munmap"); } else #endif { throw Error(2, path(), strError(), "munmap"); } } p_->mappedLength_ = size(); p_->isWriteable_ = isWriteable; if (p_->isWriteable_ && p_->switchMode(Impl::opWrite) != 0) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(16, wpath(), strError().c_str()); } else #endif { throw Error(16, path(), strError()); } } #if defined EXV_HAVE_MMAP && defined EXV_HAVE_MUNMAP int prot = PROT_READ; if (p_->isWriteable_) { prot |= PROT_WRITE; } void* rc = ::mmap(0, p_->mappedLength_, prot, MAP_SHARED, fileno(p_->fp_), 0); if (MAP_FAILED == rc) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), strError().c_str(), "mmap"); } else #endif { throw Error(2, path(), strError(), "mmap"); } } p_->pMappedArea_ = static_cast<byte*>(rc); #elif defined WIN32 && !defined __CYGWIN__ // Windows implementation // TODO: An attempt to map a file with a length of 0 (zero) fails with // an error code of ERROR_FILE_INVALID. // Applications should test for files with a length of 0 (zero) and // reject those files. DWORD dwAccess = FILE_MAP_READ; DWORD flProtect = PAGE_READONLY; if (isWriteable) { dwAccess = FILE_MAP_WRITE; flProtect = PAGE_READWRITE; } HANDLE hPh = GetCurrentProcess(); HANDLE hFd = (HANDLE)_get_osfhandle(fileno(p_->fp_)); if (hFd == INVALID_HANDLE_VALUE) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), "MSG1", "_get_osfhandle"); } else #endif { throw Error(2, path(), "MSG1", "_get_osfhandle"); } } if (!DuplicateHandle(hPh, hFd, hPh, &p_->hFile_, 0, false, DUPLICATE_SAME_ACCESS)) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), "MSG2", "DuplicateHandle"); } else #endif { throw Error(2, path(), "MSG2", "DuplicateHandle"); } } p_->hMap_ = CreateFileMapping(p_->hFile_, 0, flProtect, 0, (DWORD) p_->mappedLength_, 0); if (p_->hMap_ == 0 ) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), "MSG3", "CreateFileMapping"); } else #endif { throw Error(2, path(), "MSG3", "CreateFileMapping"); } } void* rc = MapViewOfFile(p_->hMap_, dwAccess, 0, 0, 0); if (rc == 0) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), "MSG4", "CreateFileMapping"); } else #endif { throw Error(2, path(), "MSG4", "CreateFileMapping"); } } p_->pMappedArea_ = static_cast<byte*>(rc); #else // Workaround for platforms without mmap: Read the file into memory DataBuf buf(static_cast<long>(p_->mappedLength_)); if (read(buf.pData_, buf.size_) != buf.size_) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), strError().c_str(), "FileIo::read"); } else #endif { throw Error(2, path(), strError(), "FileIo::read"); } } if (error() || eof()) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(2, wpath(), strError().c_str(), "FileIo::mmap"); } else #endif { throw Error(2, path(), strError(), "FileIo::mmap"); } } p_->pMappedArea_ = buf.release().first; p_->isMalloced_ = true; #endif return p_->pMappedArea_; }
void FileIo::transfer(BasicIo& src) { const bool wasOpen = (p_->fp_ != 0); const std::string lastMode(p_->openMode_); FileIo *fileIo = dynamic_cast<FileIo*>(&src); if (fileIo) { // Optimization if src is another instance of FileIo fileIo->close(); // Check if the file can be written to, if it already exists if (open("a+b") != 0) { // Remove the (temporary) file #ifdef EXV_UNICODE_PATH if (fileIo->p_->wpMode_ == Impl::wpUnicode) { ::_wremove(fileIo->wpath().c_str()); } else #endif { ::remove(fileIo->path().c_str()); } #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(10, wpath(), "a+b", strError().c_str()); } else #endif { throw Error(10, path(), "a+b", strError()); } } close(); bool statOk = true; mode_t origStMode = 0; std::string spf; char* pf = 0; #ifdef EXV_UNICODE_PATH std::wstring wspf; wchar_t* wpf = 0; if (p_->wpMode_ == Impl::wpUnicode) { wspf = wpath(); wpf = const_cast<wchar_t*>(wspf.c_str()); } else #endif { spf = path(); pf = const_cast<char*>(spf.c_str()); } // Get the permissions of the file, or linked-to file, on platforms which have lstat #ifdef EXV_HAVE_LSTAT # ifdef EXV_UNICODE_PATH # error EXV_UNICODE_PATH and EXV_HAVE_LSTAT are not compatible. Stop. # endif struct stat buf1; if (::lstat(pf, &buf1) == -1) { statOk = false; #ifndef SUPPRESS_WARNINGS EXV_WARNING << Error(2, pf, strError(), "::lstat") << "\n"; #endif } origStMode = buf1.st_mode; DataBuf lbuf; // So that the allocated memory is freed. Must have same scope as pf // In case path() is a symlink, get the path of the linked-to file if (statOk && S_ISLNK(buf1.st_mode)) { lbuf.alloc(buf1.st_size + 1); memset(lbuf.pData_, 0x0, lbuf.size_); pf = reinterpret_cast<char*>(lbuf.pData_); if (::readlink(path().c_str(), pf, lbuf.size_ - 1) == -1) { throw Error(2, path(), strError(), "readlink"); } // We need the permissions of the file, not the symlink if (::stat(pf, &buf1) == -1) { statOk = false; #ifndef SUPPRESS_WARNINGS EXV_WARNING << Error(2, pf, strError(), "::stat") << "\n"; #endif } origStMode = buf1.st_mode; } #else // EXV_HAVE_LSTAT Impl::StructStat buf1; if (p_->stat(buf1) == -1) { statOk = false; } origStMode = buf1.st_mode; #endif // !EXV_HAVE_LSTAT // MSVCRT rename that does not overwrite existing files #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { if (fileExists(wpf) && ::_wremove(wpf) != 0) { throw WError(2, wpf, strError().c_str(), "::_wremove"); } if (::_wrename(fileIo->wpath().c_str(), wpf) == -1) { throw WError(17, fileIo->wpath(), wpf, strError().c_str()); } ::_wremove(fileIo->wpath().c_str()); // Check permissions of new file struct _stat buf2; if (statOk && ::_wstat(wpf, &buf2) == -1) { statOk = false; #ifndef SUPPRESS_WARNINGS EXV_WARNING << Error(2, wpf, strError(), "::_wstat") << "\n"; #endif } if (statOk && origStMode != buf2.st_mode) { // Set original file permissions if (::_wchmod(wpf, origStMode) == -1) { #ifndef SUPPRESS_WARNINGS EXV_WARNING << Error(2, wpf, strError(), "::_wchmod") << "\n"; #endif } } } // if (p_->wpMode_ == Impl::wpUnicode) else #endif // EXV_UNICODE_PATH { if (fileExists(pf) && ::remove(pf) != 0) { throw Error(2, pf, strError(), "::remove"); } if (::rename(fileIo->path().c_str(), pf) == -1) { throw Error(17, fileIo->path(), pf, strError()); } ::remove(fileIo->path().c_str()); // Check permissions of new file struct stat buf2; if (statOk && ::stat(pf, &buf2) == -1) { statOk = false; #ifndef SUPPRESS_WARNINGS EXV_WARNING << Error(2, pf, strError(), "::stat") << "\n"; #endif } if (statOk && origStMode != buf2.st_mode) { // Set original file permissions if (::chmod(pf, origStMode) == -1) { #ifndef SUPPRESS_WARNINGS EXV_WARNING << Error(2, pf, strError(), "::chmod") << "\n"; #endif } } } } // if (fileIo) else { // Generic handling, reopen both to reset to start if (open("w+b") != 0) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(10, wpath(), "w+b", strError().c_str()); } else #endif { throw Error(10, path(), "w+b", strError()); } } if (src.open() != 0) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(9, src.wpath(), strError().c_str()); } else #endif { throw Error(9, src.path(), strError()); } } write(src); src.close(); } if (wasOpen) { if (open(lastMode) != 0) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(10, wpath(), lastMode.c_str(), strError().c_str()); } else #endif { throw Error(10, path(), lastMode, strError()); } } } else close(); if (error() || src.error()) { #ifdef EXV_UNICODE_PATH if (p_->wpMode_ == Impl::wpUnicode) { throw WError(18, wpath(), strError().c_str()); } else #endif { throw Error(18, path(), strError()); } } } // FileIo::transfer