CString GetErrorString(int errCode, LPTSTR name = NULL)
{
CString ret;
LPVOID lpMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&lpMsgBuf, 0, NULL);
if (lpMsgBuf) {
ret.Format(L"%s错误码%d:%s", (name?name:L""), errCode, lpMsgBuf);
LocalFree(lpMsgBuf);
} else {
ret.Format(L"%s错误码%d", (name?name:L""), errCode);
}
return ret;
}
class WinFile
{
public:
WinFile(const std::wstring &filename, bool bread)
{
open(filename, bread);
}
WinFile()
{
}
~WinFile()
{
if (isValid()) {
CloseHandle(m_hFile);
}
}
int open(const std::wstring &filename, bool bread)
{
int ret = 0;
filename_ = filename;
if (bread) {
m_hFile = CreateFile(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, 0,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
} else {
m_hFile = CreateFile(filename.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, 0,
CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0);
}
if (!isValid()) {
ret = GetLastError();
}
return ret;
}
int read(void *buf, size_t count, size_t *result = NULL)
{
assert(NULL != buf);
int ret = 0;
DWORD nread = 0;
if (ReadFile(m_hFile, buf, count, &nread, 0)) {
if (result) {
*result = nread;
}
} else {
ret = GetLastError();
}
return ret;
}
int write(const void *buf, size_t count, size_t *result = NULL)
{
assert(NULL != buf);
int ret = 0;
DWORD nwritten = 0;
if (WriteFile(m_hFile, buf, count, &nwritten, 0)) {
if (result) {
*result = nwritten;
}
} else {
ret = GetLastError();
}
return ret;
}
int seek(size_t n)
{
LARGE_INTEGER fileSize;
GetFileSizeEx(m_hFile, &fileSize);
if (fileSize.QuadPart < n) {
return -1;
}
LARGE_INTEGER li;
li.QuadPart = n;
li.LowPart = SetFilePointer(m_hFile, li.LowPart, &li.HighPart, FILE_BEGIN);
if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
return GetLastError();
}
return 0;
}
DWORD size()
{
return GetFileSize(m_hFile, NULL);
}
bool isValid() { return m_hFile != INVALID_HANDLE_VALUE; }
std::wstring filename() const { return filename_; }
private:
HANDLE m_hFile;
std::wstring filename_;
};
void CSmallFileDlg::OnBnClickedOk()
{
WinFile fr(L"C:\\Users\\jiaw\\Desktop\\xyz.flv", true);
WinFile fw(L"C:\\Users\\jiaw\\Desktop\\xyz2.flv", false);
char buf[65536];
size_t result;
DWORD total = fr.size();
DWORD nread = 0;
while (nread != total) {
int ret = fr.read(buf, sizeof(buf), &result);
if (0 != ret) {
MessageBox(GetErrorString(ret));
break;
}
nread += result;
fr.seek(nread); // 设置下次的读取位置
ret = fw.write(buf, result);
if (0 != ret) {
MessageBox(GetErrorString(ret));
break;
} else {
fw.seek(nread); // 设置下次的写入位置
}
}
CDialogEx::OnOK();
}