window 下大文件读写

#ifdef WIN32 #include <iostream> using namespace std; class WinLargeFile { public: WinLargeFile(std::string path, __int64 offset, char a) { _path = path; _wpath = s2ws(_path); switch (a) { case 'r': hFile = CreateFile(_wpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == NULL) { DWORD ec = GetLastError(); } break; case 'w': hFile = CreateFile(_wpath.c_str(), GENERIC_WRITE, 0, NULL, offset > 0 ? OPEN_EXISTING : CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == NULL) { DWORD ec = GetLastError(); } break; default: break; } cout << "open handle" << endl; } ~WinLargeFile() { cout << "close handle" << endl; CloseHandle(hFile); } int Write(char* buffer, __int64 offset, int buflen) { /*HANDLE hFile = CreateFile(_wpath.c_str(), GENERIC_WRITE, 0, NULL, offset > 0 ? OPEN_EXISTING : CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == NULL) { DWORD ec = GetLastError(); return -1; } */ // //GetFileSize: // //DWORD dwFileSizeHigh; //__int64 qwFileSize = GetFileSize(hFile, &dwFileSizeHigh); //qwFileSize |= (((__int64)dwFileSizeHigh) << 32); // if(__FileSeek(hFile, offset, FILE_BEGIN) == -1) { CloseHandle(hFile); return -1; } // DWORD dwWritenLen = 0; if(! WriteFile(hFile, buffer, buflen, &dwWritenLen, NULL)) { CloseHandle(hFile); return -1; } // //CloseHandle(hFile); return dwWritenLen & 0xFFFFFFFF; } int Read(char* buffer, __int64 offset, unsigned int bufMaxLen) { /*HANDLE hFile = CreateFile(_wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == NULL) { DWORD ec = GetLastError(); return -1; } */ // //GetFileSize: // //DWORD dwFileSizeHigh; //__int64 qwFileSize = GetFileSize(hFile, &dwFileSizeHigh); //qwFileSize |= (((__int64)dwFileSizeHigh) << 32); // if(__FileSeek(hFile, offset, FILE_BEGIN) == -1) { CloseHandle(hFile); return -1; } // DWORD dwBytesRead = 0; if (! ReadFile(hFile, buffer, bufMaxLen, &dwBytesRead, NULL)) { CloseHandle(hFile); return -1; } // DWORD d = GetLastError(); //CloseHandle(hFile); // return (dwBytesRead & 0xFFFFFFFF); } std::wstring s2ws(const std::string& s) { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); std::wstring r(buf); delete[] buf; return r; } private: __int64 __FileSeek(HANDLE hf, __int64 distance, DWORD MoveMethod) { LARGE_INTEGER li; li.QuadPart = distance; li.LowPart = SetFilePointer (hf, li.LowPart, &li.HighPart, MoveMethod); // if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) { li.QuadPart = -1; } // return li.QuadPart; } private: std::string _path; std::wstring _wpath; HANDLE hFile; }; #endif

你可能感兴趣的:(String,File,null,buffer,Path,distance)