本文整理汇总了C++中ReadFile函数的典型用法代码示例。如果您正苦于以下问题:C++ ReadFile函数的具体用法?C++ ReadFile怎么用?C++ ReadFile使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ReadFile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: PipeServer
void PipeServer()
{
HANDLE hPipeToSrv;
HANDLE hPipeFromSrv;
LPTSTR pipeNameToSrv= _T("\\\\.\\pipe\\ToSrvPipe");
hPipeToSrv = CreateNamedPipe(
pipeNameToSrv ,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
PIPE_UNLIMITED_INSTANCES,
nBuff,
nBuff,
50,//Timeout - always send straight away.
NULL);
if( hPipeToSrv == INVALID_HANDLE_VALUE)
return;
LPTSTR pipeNameFromSrv= __T("\\\\.\\pipe\\FromSrvPipe");
hPipeFromSrv = CreateNamedPipe(
pipeNameFromSrv ,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
PIPE_UNLIMITED_INSTANCES,
nBuff,
nBuff,
50,//Timeout - always send straight away.
NULL);
if( hPipeFromSrv == INVALID_HANDLE_VALUE)
return;
BOOL bConnected;
BOOL bSuccess;
DWORD cbBytesRead;
DWORD cbBytesWritten;
CHAR chRequest[ nBuff ];
CHAR chResponse[ nBuff ];
int jj=0;
for(;;)
{
printf( "Obtaining pipe\n" );
bConnected = ConnectNamedPipe(hPipeToSrv, NULL) ?
TRUE : (GetLastError()==ERROR_PIPE_CONNECTED );
printf( "Obtained to-srv %i\n", bConnected );
bConnected = ConnectNamedPipe(hPipeFromSrv, NULL) ?
TRUE : (GetLastError()==ERROR_PIPE_CONNECTED );
printf( "Obtained from-srv %i\n", bConnected );
if( bConnected )
{
for(;;)
{
printf( "About to read\n" );
bSuccess = ReadFile( hPipeToSrv, chRequest, nBuff, &cbBytesRead, NULL);
chRequest[ cbBytesRead] = '\0';
if( !bSuccess || cbBytesRead==0 )
break;
printf( "Rxd %s\n", chRequest );
DoSrv( chRequest );
jj++;
while( true )
{
int nWritten = DoSrvMore( chResponse, nBuff );
if( nWritten <= 1 )
break;
WriteFile( hPipeFromSrv, chResponse, nWritten-1, &cbBytesWritten, NULL);
}
//FlushFileBuffers( hPipeFromSrv );
}
FlushFileBuffers( hPipeToSrv );
DisconnectNamedPipe( hPipeToSrv );
FlushFileBuffers( hPipeFromSrv );
DisconnectNamedPipe( hPipeFromSrv );
break;
}
else
{
CloseHandle( hPipeToSrv );
CloseHandle( hPipeFromSrv );
}
}
CloseHandle( hPipeToSrv );
CloseHandle( hPipeFromSrv );
}
示例2: git_free_exclude_list
int CGitIgnoreItem::FetchIgnoreList(const CString &projectroot, const CString &file, bool isGlobal)
{
if (this->m_pExcludeList)
{
git_free_exclude_list(m_pExcludeList);
m_pExcludeList=NULL;
}
free(m_buffer);
m_buffer = nullptr;
this->m_BaseDir.Empty();
if (!isGlobal)
{
CString base = file.Mid(projectroot.GetLength() + 1);
base.Replace(_T('\\'), _T('/'));
int start = base.ReverseFind(_T('/'));
if(start > 0)
{
base = base.Left(start);
this->m_BaseDir = CUnicodeUtils::GetMulti(base, CP_UTF8) + "/";
}
}
{
if(g_Git.GetFileModifyTime(file, &m_LastModifyTime))
return -1;
if(git_create_exclude_list(&this->m_pExcludeList))
return -1;
CAutoFile hfile = CreateFile(file,
GENERIC_READ,
FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (!hfile)
return -1 ;
DWORD size=0,filesize=0;
filesize=GetFileSize(hfile, NULL);
if(filesize == INVALID_FILE_SIZE)
return -1;
m_buffer = new BYTE[filesize + 1];
if (m_buffer == NULL)
return -1;
if (!ReadFile(hfile, m_buffer, filesize, &size, NULL))
return GetLastError();
BYTE *p = m_buffer;
int line = 0;
for (DWORD i = 0; i < size; ++i)
{
if (m_buffer[i] == '\n' || m_buffer[i] == '\r' || i == (size - 1))
{
if (m_buffer[i] == '\n' || m_buffer[i] == '\r')
m_buffer[i] = 0;
if (i == size - 1)
m_buffer[size] = 0;
if(p[0] != '#' && p[0] != 0)
git_add_exclude((const char*)p,
this->m_BaseDir,
m_BaseDir.GetLength(),
this->m_pExcludeList, ++line);
p = m_buffer + i + 1;
}
}
}
return 0;
}
示例3: VerifyMoneyHubList
int VerifyMoneyHubList(const char *path, const char* CHKFileName, char *message)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
unsigned char *content;
int contentLength;
int ret;
//assert(path && message);
std::string strFile = CHKFileName;
// 读文件
hFile = CreateFile(strFile.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
// 读取文件长度
DWORD dwLength = GetFileSize(hFile, NULL);
unsigned char* lpBuffer = new unsigned char[dwLength + 1];
if(lpBuffer==NULL)
{
strcpy(message,"内存空间满");
return -3001;
}
DWORD dwRead = 0;
if(!ReadFile(hFile, lpBuffer, dwLength, &dwRead, NULL))
{
delete []lpBuffer;
strcpy(message,"读财金汇软件的完整性信息失败");
return -3002;
}
CloseHandle(hFile);
content=new unsigned char[dwRead];
if (content==NULL)
{
delete []lpBuffer;
strcpy(message,"内存空间满");
return -3001;
}
contentLength=unPackCHK(lpBuffer,dwRead,content);
delete []lpBuffer;
if (contentLength<0)
{
strcpy(message,"检验财金汇软件的完整性信息失败");
return -3003;
}
ret=CheckMoneyHubList(content,contentLength,path,message);
delete []content;
return ret;
} else {
strcpy(message,"找不到财金汇软件的完整性信息");
return -3000;
}
}
示例4: CreateFile
BOOL CDlgExportHistory::ExportHistory(LPCSTR pszFile, fs::list <fsDLHistoryRecord*> &vpHist, BOOL bAppend)
{
HANDLE hFile = CreateFile (pszFile, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
return FALSE;
CString str;
if (bAppend && GetLastError () == ERROR_ALREADY_EXISTS)
{
DWORD dwSize = GetFileSize (hFile, NULL);
if (dwSize > 10000)
{
SetFilePointer (hFile, dwSize - 10000, NULL, FILE_BEGIN);
dwSize = 10000;
}
DWORD dw;
LPSTR psz = new char [dwSize+1];
ReadFile (hFile, psz, dwSize, &dw, NULL);
psz [dwSize] = 0;
int nLen = lstrlen (psz);
if (nLen != (int) dwSize)
{
CloseHandle (hFile);
return FALSE;
}
LPSTR psz2 = psz + nLen - 7;
while (psz2 != psz)
{
if (_memicmp (psz2, "</body>", 7) == 0)
{
*psz2 = 0;
break;
}
*psz2--;
}
if (psz2 == psz)
{
CloseHandle (hFile);
return FALSE;
}
SetFilePointer (hFile, (psz2 - psz) - nLen, NULL, FILE_END);
SetEndOfFile (hFile);
delete [] psz;
}
else
{
SetEndOfFile (hFile);
str = "<html>\n";
str += "<style type=\"text/css\">\n";
str += "<!--\n";
str += "H3 { font-size: 19px; font-family: Tahoma; color: #cc0000;}\n";
str += "TR { font-size: 12px; font-family: Tahoma; color: #000033}\n";
str += "TD { font-size: 12px; font-family: Tahoma; color: #000033}\n";
str += "A,A:visited,A:active { text-decoration: none; }\n";
str += "A:hover { text-decoration: underline; }\n";
str += "-->\n";
str += "</style>\n";
str += "<body>\n";
str += "<h3>";
str += LS (L_FDMHIST);
str += "</h3>\n";
}
for (int i = 0; i < vpHist.size (); i++)
{
fsDLHistoryRecord* rec = vpHist [i];
str += "<table width=\"75%\" border=\"1\">\n";
str += "<tr><td width=\"180\">";
str += LS (L_URLOFDOWNLOAD);
str += ":</td>";
str += "<td><a href=\"";
str += rec->strURL;
str += "\"> ";
str += rec->strURL;
str += "</a></td></tr>\n";
//.........这里部分代码省略.........
示例5: _T
// This method is assumed to be called with m_SharedMutex locked.
int CGitHeadFileList::GetPackRef(const CString &gitdir)
{
CString PackRef = g_AdminDirMap.GetAdminDir(gitdir) + _T("packed-refs");
__int64 mtime;
if (g_Git.GetFileModifyTime(PackRef, &mtime))
{
//packed refs is not existed
this->m_PackRefFile.Empty();
this->m_PackRefMap.clear();
return 0;
}
else if(mtime == m_LastModifyTimePackRef)
{
return 0;
}
else
{
this->m_PackRefFile = PackRef;
this->m_LastModifyTimePackRef = mtime;
}
m_PackRefMap.clear();
CAutoFile hfile = CreateFile(PackRef,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
nullptr,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
nullptr);
if (!hfile)
return -1;
DWORD filesize = GetFileSize(hfile, nullptr);
if (filesize == 0)
return -1;
DWORD size = 0;
std::unique_ptr<char[]> buff(new char[filesize]);
ReadFile(hfile, buff.get(), filesize, &size, nullptr);
if (size != filesize)
return -1;
CString hash;
CString ref;
for (DWORD i = 0; i < filesize;)
{
hash.Empty();
ref.Empty();
if (buff[i] == '#' || buff[i] == '^')
{
while (buff[i] != '\n')
{
++i;
if (i == filesize)
break;
}
++i;
}
if (i >= filesize)
break;
while (buff[i] != ' ')
{
hash.AppendChar(buff[i]);
++i;
if (i == filesize)
break;
}
++i;
if (i >= filesize)
break;
while (buff[i] != '\n')
{
ref.AppendChar(buff[i]);
++i;
if (i == filesize)
break;
}
if (!ref.IsEmpty())
m_PackRefMap[ref] = hash;
while (buff[i] == '\n')
{
++i;
if (i == filesize)
break;
}
}
return 0;
}
示例6: console_read
// returns 0 iff read not complete, >0 bytes read, <0 on error
int
console_read(console_t console, char *buf, int buflen) {
int i, err;
DWORD dw=0;
int lastError;
int n = 0;
do {
// finish the previous overlapped read
assertb( console->read_pending );
if( console->read_result ) {
dw = console->read_result;
}
else {
i = GetOverlappedResult(console->read_handle, &console->read_overlap,
&dw, FALSE);
if( !i && GetLastError() == ERROR_IO_INCOMPLETE ) {
n = 0;
err = 0;
break;
}
assertb_syserr(i);
console->read_pending = 0;
}
n = 0;
while(1) {
i = MIN((int)dw, buflen - n);
memcpy(buf + n, console->read_buf, i);
if( i < dw ) {
i = dw - i;
console->read_result = 5;
memcpy(console->read_buf, console->read_buf + i, i);
SetEvent(console->read_event);
break;
}
// start a new overlapped read
memset(&console->read_overlap, 0, sizeof(console->read_overlap));
ResetEvent(console->read_event);
console->read_overlap.hEvent = console->read_event;
console->read_result = 0;
dw = sizeof(console->read_buf);
debug(DEBUG_INFO,
("console_read reading dw=%ld\n", dw));
i = ReadFile(console->read_handle, console->read_buf, sizeof(console->read_buf),
&dw, &console->read_overlap);
lastError = GetLastError();
debug(DEBUG_INFO,
("console_read"
" i=%d"
" dw=%ld"
" GetLastError()=%d"
" ERROR_IO_PENDING=%d"
" IsSet(read_event)=%d"
"\n"
, i, (long)dw, lastError, ERROR_IO_PENDING
, (int)(WaitForSingleObject(console->read_overlap.hEvent, 0) == WAIT_OBJECT_0)
));
if( i ) {
continue;
}
else if( lastError == ERROR_IO_PENDING ) {
console->read_pending = 1;
console->read_result = 0;
break;
}
else {
assertb_syserr(0);
}
}
err = 0;
} while(0);
return err ? err : n;
}
示例7: request
//.........这里部分代码省略.........
* at all, we get it.
*/
for (;;) {
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
tvout.tv_sec = TIMEOUT_SEC;
tvout.tv_usec = TIMEOUT_USEC;
n = select(sockfd + 1, &fdset, (fd_set *)0,
(fd_set *)0, &tvout);
if (n < 0) {
if (errno != EINTR)
msyslog(LOG_ERR, "select() fails: %m");
return 0;
} else if (n == 0) {
#ifdef DEBUG
if (debug)
msyslog(LOG_INFO, "ntp_intres select() returned 0.");
#endif
return 0;
}
#ifndef SYS_WINNT
n = recv(sockfd, (char *)&reqpkt, sizeof(reqpkt), 0);
if (n <= 0) {
if (n < 0) {
msyslog(LOG_ERR, "recv() fails: %m");
return 0;
}
continue;
}
#else /* Overlapped I/O used on non-blocking sockets on Windows NT */
ret = ReadFile((HANDLE)sockfd, (char *)&reqpkt, sizeof(reqpkt),
NULL, (LPOVERLAPPED)&overlap);
if ((ret == FALSE) && (GetLastError() != ERROR_IO_PENDING)) {
msyslog(LOG_ERR, "ReadFile() fails: %m");
return 0;
}
dwWait = WaitForSingleObject(hReadWriteEvent, (DWORD) TIMEOUT_SEC * 1000);
if ((dwWait == WAIT_FAILED) || (dwWait == WAIT_TIMEOUT)) {
if (dwWait == WAIT_FAILED) {
msyslog(LOG_ERR, "WaitForSingleObject for ReadFile fails: %m");
return 0;
}
continue;
}
if (!GetOverlappedResult((HANDLE)sockfd, (LPOVERLAPPED)&overlap,
(LPDWORD)&NumberOfBytesRead, FALSE)) {
msyslog(LOG_ERR, "GetOverlappedResult fails: %m");
return 0;
}
n = NumberOfBytesRead;
#endif /* SYS_WINNT */
/*
* Got one. Check through to make sure it is what
* we expect.
*/
if (n < RESP_HEADER_SIZE) {
msyslog(LOG_ERR, "received runt response (%d octets)",
n);
continue;
}
if (!ISRESPONSE(reqpkt.rm_vn_mode)) {
示例8: CreateFile
bool Crypter::crypt(const char *infile, const char *outfile){
// variables
DWORD dwOldProt, bytes;
// open it and get the size
HANDLE hFile = CreateFile(infile, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
if (!hFile){
MYPRINTF("Unable to open file\n");
return false;
}
DWORD dwFileSize = GetFileSize(hFile, 0);
// load in memory
LPBYTE fileBuffer = (LPBYTE) malloc(dwFileSize);
ReadFile(hFile, fileBuffer, dwFileSize, &bytes, 0);
CloseHandle(hFile);
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER) fileBuffer;
// check if it is valid PE, i would say that this is merely a proper check, for a proper one you would need to calculate all the RVA's and see if they are valid
if(dosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
MYPRINTF("IMAGE_DOS_SIGNATURE\n");
return false;
}
PIMAGE_NT_HEADERS ntHeaders = (PIMAGE_NT_HEADERS) (fileBuffer + dosHeader->e_lfanew);
if(ntHeaders->Signature != IMAGE_NT_SIGNATURE){
MYPRINTF("IMAGE_NT_SIGNATURE\n");
return false;
}
PIMAGE_SECTION_HEADER sectionHeader = (PIMAGE_SECTION_HEADER) SECHDROFFSET(fileBuffer);
#define TEXT_SECTION ".text"
while(memcmp(sectionHeader->Name, TEXT_SECTION, strlen(TEXT_SECTION))) // get the ".text" section header
sectionHeader++;
DWORD dwVSize = sectionHeader->Misc.VirtualSize; // the virtual size of the section, later this will be used as chunksize in our stub, after proper alignment
DWORD dwSectionSize = sectionHeader->SizeOfRawData; // speaks for itself
DWORD dwStubSize; // the stubsize, in bytes
if (Crypter::evadeSandbox){
dwStubSize = (DWORD) _end_evade_sandbox - (DWORD) _xor_block_evade_sandbox; // the stubsize, in bytes
} else {
dwStubSize = (DWORD) _end - (DWORD) _xor_block; // the stubsize, in bytes
}
LPBYTE sectionBuffer = (LPBYTE) malloc(dwSectionSize); // allocate memory enough to hold our raw section data
memcpy(sectionBuffer, fileBuffer + sectionHeader->PointerToRawData, dwSectionSize); // ... copy the data
_xor_chunk(sectionBuffer, dwSectionSize, 256); // aaand encrypt it! you can use different block sizes here - 8, 16, 32, 64, 128, 256, 512...
memset(sectionBuffer + sectionHeader->Misc.VirtualSize, 0, (dwSectionSize - sectionHeader->Misc.VirtualSize)); // fill with zeros after the end of actual data
// copy back the data
memcpy(fileBuffer + sectionHeader->PointerToRawData, sectionBuffer, dwSectionSize); // ... copy the data
free(sectionBuffer);
DWORD oep = ntHeaders->OptionalHeader.AddressOfEntryPoint + ntHeaders->OptionalHeader.ImageBase; // the original entry point, this is a linear address
DWORD seg = sectionHeader->VirtualAddress + ntHeaders->OptionalHeader.ImageBase; // the section address, you guessed right, this too is a linear one
DWORD bsz = 256; // you know what this is
while(dwVSize % bsz) // we need to align it to block size
dwVSize++;
if (Crypter::evadeSandbox){
VirtualProtect(_xor_block_evade_sandbox, dwStubSize, PAGE_EXECUTE_READWRITE, &dwOldProt); // to be able to update the stub...
} else {
VirtualProtect(_xor_block, dwStubSize, PAGE_EXECUTE_READWRITE, &dwOldProt); // to be able to update the stub...
}
// and update it, blah, blah, blah...
if (Crypter::evadeSandbox){
memcpy((void *)((unsigned long) _stub_evade_sandbox + OEP_o), &oep, 4);
memcpy((void *)((unsigned long) _stub_evade_sandbox + SEG_o), &seg, 4);
memcpy((void *)((unsigned long) _stub_evade_sandbox + BSZ_o), &bsz, 4);
memcpy((void *)((unsigned long) _stub_evade_sandbox + SZ_o), &dwVSize, 4);
} else {
memcpy((void *)((unsigned long) _stub + OEP_o), &oep, 4);
memcpy((void *)((unsigned long) _stub + SEG_o), &seg, 4);
memcpy((void *)((unsigned long) _stub + BSZ_o), &bsz, 4);
memcpy((void *)((unsigned long) _stub + SZ_o), &dwVSize, 4);
}
Crypter::section = new char [6];
Random::createRandomName(COUNTOF(Crypter::section), Crypter::section);
char* resDll;
DWORD szResDll;
if (Crypter::evadeSandbox){
if (!Crypter::insertSectionConfigInPE(fileBuffer, dwFileSize, _xor_block_evade_sandbox, dwStubSize + sizeof(int), (PVOID*)(&resDll), &szResDll )){
MYPRINTF("problem with injection\n");
delete Crypter::section;
return false;
}
} else {
if (!Crypter::insertSectionConfigInPE(fileBuffer, dwFileSize, _xor_block, dwStubSize + sizeof(int), (PVOID*)(&resDll), &szResDll )){
MYPRINTF("problem with injection\n");
delete Crypter::section;
return false;
}
}
//.........这里部分代码省略.........
示例9: hx_get_child_data
static int
hx_get_child_data(hx_logsys_t *log,
hx_process_t *child,
unsigned char *buffer,
long *buflen)
{
const char *rname = "hx_get_child_data ()";
long rem = *buflen;
long totRead = 0;
unsigned char *pbuf = buffer;
unsigned char *errStr;
int timeout;
int retval;
#ifdef _HX_WIN32_
DWORD read = 0;
HANDLE out;
#elif defined(_HX_UNIX_)
int out;
#endif
hx_log_msg(log, HX_LCALL, rname, "Called");
/* Retrieve the server timeout from the
config table */
timeout = atoi((unsigned char *)hx_get_conf_val(log, IDX_SERVER_TIMEOUT));
#ifdef _HX_WIN32_
out = child->childHandles[HX_STDOUT];
while(1)
{
retval = ReadFile(out, pbuf, rem, &read, NULL);
if(!retval || read == 0)
{
/* End of file Encountered */
break;
}
pbuf += read;
rem -= read;
totRead += read;
if(rem <= 0)
return HX_MOREDATA;
}
#elif defined (_HX_UNIX_)
out = child->parentStreams[HX_STDOUT];
while(1)
{
retval = hx_readNonBlock(out, timeout, pbuf, rem);
if(!retval || retval < 0)
{
/* End of file Encountered */
if(retval < 0)
{
switch(retval)
{
case HX_ERR_CHILDREAD_TIMED_OUT:
errStr = "Child process read timed out";
break;
case HX_ERR_CHILDWRITE_TIMED_OUT:
errStr = "Child process write timed out";
break;
case HX_ERR_CHILDREAD:
errStr = "Error reading from child pipe";
break;
case HX_ERR_IOCTL:
errStr = "Error performing ioctl on pipe";
break;
case HX_ERR_SELECT:
errStr = "Error performing select";
break;
default:
errStr = "Unkown error reading from pipe";
break;
}
hx_log_msg(log,
HX_LERRO,
rname,
"%s [%s]",
errStr,
strerror(errno));
}
break;
}
//.........这里部分代码省略.........
示例10: CompileShader
static bool CompileShader(wchar_t *shaderFixPath, wchar_t *fileName, const char *shaderModel, UINT64 hash, wstring shaderType, FILETIME* timeStamp,
_Outptr_ D3D10Base::ID3DBlob** pCode)
{
*pCode = nullptr;
wchar_t fullName[MAX_PATH];
wsprintf(fullName, L"%s\\%s", shaderFixPath, fileName);
HANDLE f = CreateFile(fullName, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (f == INVALID_HANDLE_VALUE)
{
LogInfo(" ReloadShader shader not found: %ls\n", fullName);
return true;
}
DWORD srcDataSize = GetFileSize(f, 0);
char *srcData = new char[srcDataSize];
DWORD readSize;
FILETIME curFileTime;
if (!ReadFile(f, srcData, srcDataSize, &readSize, 0)
|| !GetFileTime(f, NULL, NULL, &curFileTime)
|| srcDataSize != readSize)
{
LogInfo(" Error reading txt file.\n");
return true;
}
CloseHandle(f);
// Check file time stamp, and only recompile shaders that have been edited since they were loaded.
// This dramatically improves the F10 reload speed.
if (!CompareFileTime(timeStamp, &curFileTime))
{
return false;
}
*timeStamp = curFileTime;
LogInfo(" >Replacement shader found. Re-Loading replacement HLSL code from %ls\n", fileName);
LogInfo(" Reload source code loaded. Size = %d\n", srcDataSize);
LogInfo(" compiling replacement HLSL code with shader model %s\n", shaderModel);
D3D10Base::ID3DBlob* pByteCode = nullptr;
D3D10Base::ID3DBlob* pErrorMsgs = nullptr;
HRESULT ret = D3D10Base::D3DCompile(srcData, srcDataSize, "wrapper1349", 0, ((D3D10Base::ID3DInclude*)(UINT_PTR)1),
"main", shaderModel, D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, &pByteCode, &pErrorMsgs);
delete srcData; srcData = 0;
// bo3b: pretty sure that we do not need to copy the data. That data is what we need to pass to CreateVertexShader
// Example taken from: http://msdn.microsoft.com/en-us/library/windows/desktop/hh968107(v=vs.85).aspx
//char *pCode = 0;
//SIZE_T pCodeSize;
//if (pCompiledOutput)
//{
// pCodeSize = pCompiledOutput->GetBufferSize();
// pCode = new char[pCodeSize];
// memcpy(pCode, pCompiledOutput->GetBufferPointer(), pCodeSize);
// pCompiledOutput->Release(); pCompiledOutput = 0;
//}
LogInfo(" compile result of replacement HLSL shader: %x\n", ret);
if (gLogFile && pErrorMsgs)
{
LPVOID errMsg = pErrorMsgs->GetBufferPointer();
SIZE_T errSize = pErrorMsgs->GetBufferSize();
LogInfo("--------------------------------------------- BEGIN ---------------------------------------------\n");
fwrite(errMsg, 1, errSize - 1, gLogFile);
LogInfo("---------------------------------------------- END ----------------------------------------------\n");
pErrorMsgs->Release();
}
if (FAILED(ret))
{
if (pByteCode)
{
pByteCode->Release();
pByteCode = 0;
}
return true;
}
// Write replacement .bin if necessary
if (G->CACHE_SHADERS && pByteCode)
{
wchar_t val[MAX_PATH];
wsprintf(val, L"%ls\\%08lx%08lx-%ls_replace.bin", shaderFixPath, (UINT32)(hash >> 32), (UINT32)(hash), shaderType.c_str());
FILE *fw;
_wfopen_s(&fw, val, L"wb");
if (gLogFile)
{
char fileName[MAX_PATH];
wcstombs(fileName, val, MAX_PATH);
if (fw)
LogInfo(" storing compiled shader to %s\n", fileName);
else
//.........这里部分代码省略.........
示例11: ZeroMemory
void AdbManager::internal_scan_timeout(void* arg)
{
g_adb_manager->mLocalTimer = NULL;
//scan
for (int i = 0; i < 1 && g_adb_manager->mShouldScan; i++)
{
HANDLE pipe_read, pipe_write;
SECURITY_ATTRIBUTES sa;
STARTUPINFO startup;
PROCESS_INFORMATION pinfo;
char program_path[MAX_PATH];
int ret;
ZeroMemory(&sa, sizeof(sa));
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
/* create pipe, and ensure its read handle isn't inheritable */
ret = MyCreatePipeEx(&pipe_read, &pipe_write, &sa, 0);
if (!ret) {
fprintf(stderr, "CreatePipe() failure, error %ld\n", GetLastError());
break;
}
SetHandleInformation(pipe_read, HANDLE_FLAG_INHERIT, 0);
ZeroMemory(&startup, sizeof(startup));
startup.cb = sizeof(startup);
startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
startup.hStdOutput = pipe_write;
startup.hStdError = pipe_write;// GetStdHandle(STD_ERROR_HANDLE);
startup.dwFlags = STARTF_USESTDHANDLES;
ZeroMemory(&pinfo, sizeof(pinfo));
/* get path of current program */
GetModuleFileName(NULL, program_path, sizeof(program_path));
char * ch = strrchr(program_path, '\\');
//if (ch){ ch++; strcpy(ch, "adb.exe devices"); }
if (ch){ ch++; strcpy(ch, "adb.exe devices"); }
ret = CreateProcess(
NULL, /* program path */
program_path,
/* the fork-server argument will set the
debug = 2 in the child */
NULL, /* process handle is not inheritable */
NULL, /* thread handle is not inheritable */
TRUE, /* yes, inherit some handles */
DETACHED_PROCESS, /* the new process doesn't have a console */
NULL, /* use parent's environment block */
NULL, /* use parent's starting directory */
&startup, /* startup info, i.e. std handles */
&pinfo);
CloseHandle(pipe_write);
if (!ret) {
fprintf(stderr, "CreateProcess failure, error %ld\n", GetLastError());
CloseHandle(pipe_read);
break;
}
CloseHandle(pinfo.hThread);
char temp[65536];
int total_count = 0;
DWORD count;
ULONGLONG start_time = GetTickCount64();
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(OVERLAPPED));
do{
count = 0;
ret = ReadFile(pipe_read, temp + total_count, sizeof(temp)-total_count, &count, &overlapped);
total_count += count;
//if (GetTickCount64() - start_time > 10 * 1000){ break; }
if (!ret) {
int err = GetLastError();
if (err == ERROR_IO_PENDING)
{
Sleep(1000);
GetOverlappedResult(pipe_read, &overlapped, &count, FALSE);
total_count += count;
continue;
}
fprintf(stderr, "could not read ok from ADB Server, error = %ld\n", err);
break;
}
else{
Sleep(100);
}
} while (1);
CloseHandle(pipe_read);
TerminateProcess(pinfo.hProcess, 0);
CloseHandle(pinfo.hProcess);
g_adb_manager->parse_device(temp);
break;
}
//.........这里部分代码省略.........
示例12: HRESULT_FROM_WIN32
//=============================================================================
// チャンクのチェック
//=============================================================================
HRESULT Sound::CheckChunk(HANDLE file,DWORD format,DWORD *pChunkSize,DWORD *pChunkDataPosition)
{
HRESULT hr = S_OK;
DWORD read;
DWORD chunkType;
DWORD chunkDataSize;
DWORD RIFFDataSize = 0;
DWORD fileType;
DWORD bytesRead = 0;
DWORD offset = 0;
if (SetFilePointer(file,0,NULL,FILE_BEGIN) == INVALID_SET_FILE_POINTER)
{// ファイルポインタを先頭に移動
return HRESULT_FROM_WIN32(GetLastError());
}
while (hr == S_OK)
{
if (ReadFile(file,&chunkType,sizeof(DWORD),&read,NULL) == 0)
{// チャンクの読み込み
hr = HRESULT_FROM_WIN32(GetLastError());
}
if (ReadFile(file,&chunkDataSize,sizeof(DWORD),&read,NULL) == 0)
{// チャンクデータの読み込み
hr = HRESULT_FROM_WIN32(GetLastError());
}
switch (chunkType)
{
case 'FFIR':
RIFFDataSize = chunkDataSize;
chunkDataSize = 4;
if (ReadFile(file,&fileType,sizeof(DWORD),&read,NULL) == 0)
{// ファイルタイプの読み込み
hr = HRESULT_FROM_WIN32(GetLastError());
}
break;
default:
if (SetFilePointer(file,chunkDataSize,NULL,FILE_CURRENT) == INVALID_SET_FILE_POINTER)
{// ファイルポインタをチャンクデータ分移動
return HRESULT_FROM_WIN32(GetLastError());
}
}
offset += sizeof(DWORD) * 2;
if (chunkType == format)
{
*pChunkSize = chunkDataSize;
*pChunkDataPosition = offset;
return S_OK;
}
offset += chunkDataSize;
if (bytesRead >= RIFFDataSize)
{
return S_FALSE;
}
}
return S_OK;
}
示例13: ReadBlock
BOOL ReadBlock(HANDLE hPortalHandle, unsigned int block, unsigned char data[0x10],
BOOL isNEWskylander) {
RWBlock req, res;
BOOL running = TRUE;
BOOL gotData;
OVERLAPPED ovlr;
DWORD err;
unsigned char followup;
if(block >= 0x40) {
return FALSE;
}
printf(".");
for(int retries = 0; retries < 3; retries++)
{
// Send query request
memset(req.buf, 0, rw_buf_size);
req.buf[1] = 'Q';
if(isNEWskylander) {
followup = 0x11;
if(block == 0) {
req.buf[2] = 0x21;
} else {
req.buf[2] = followup;
}
} else {
followup = 0x10;
if(block == 0) {
req.buf[2] = 0x20;
} else {
req.buf[2] = followup;
}
}
req.buf[3] = (unsigned char)block;
memset(&(res.buf), 0, rw_buf_size);
// Must set the Offset and OffsetHigh members of the OVERLAPPED structure to zero.
memset(&ovlr, 0, sizeof(ovlr));
ovlr.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); // read event
int i=0;
gotData = FALSE;
Write(hPortalHandle, &req);
// Don't wait. Start polling for result immediately
for(; i<40; ++i) // try up to 40 reads
{
BOOL b = ReadFile(hPortalHandle, res.buf, rw_buf_size, &(res.dwBytesTransferred), &ovlr);
if(!b)
{
/* failed to get data immediately*/
err = GetLastError();
if(err == ERROR_IO_PENDING)
{
/* wait for data */
b = GetOverlappedResult(hPortalHandle, &ovlr, &res.dwBytesTransferred, TRUE);
if(!b)
{
/* wait failed */
break;
}
}
else
{
/* some other error */
break;
}
}
if(res.dwBytesTransferred > 0)
{
/* has data */
if(res.buf[1] == 'Q' && res.buf[3] == (unsigned char)block) {
// Got our query back
if(res.buf[2] == followup) {
/* got the query back with no error */
gotData = TRUE;
break;
}
}
res.buf[0] = 0; // make sure we are using report 0
}
} /* read loop */
CloseHandle(ovlr.hEvent);
if(gotData) {
break;
}
} // retries
//.........这里部分代码省略.........
示例14: FlushDNSMailSlotMonitor
//MailSlot of flush DNS cache Monitor
bool __fastcall FlushDNSMailSlotMonitor(
void)
{
//System security setting
std::shared_ptr<char> ACL_Buffer(new char[FILE_BUFFER_SIZE]());
memset(ACL_Buffer.get(), 0, FILE_BUFFER_SIZE);
SECURITY_ATTRIBUTES SecurityAttributes;
SECURITY_DESCRIPTOR SecurityDescriptor;
memset(&SecurityAttributes, 0, sizeof(SECURITY_ATTRIBUTES));
memset(&SecurityDescriptor, 0, sizeof(SECURITY_DESCRIPTOR));
PSID SID_Value = nullptr;
InitializeSecurityDescriptor(&SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
InitializeAcl((PACL)ACL_Buffer.get(), FILE_BUFFER_SIZE, ACL_REVISION);
ConvertStringSidToSidW(SID_ADMINISTRATORS_GROUP, &SID_Value);
AddAccessAllowedAce((PACL)ACL_Buffer.get(), ACL_REVISION, GENERIC_ALL, SID_Value);
SetSecurityDescriptorDacl(&SecurityDescriptor, true, (PACL)ACL_Buffer.get(), false);
SecurityAttributes.lpSecurityDescriptor = &SecurityDescriptor;
SecurityAttributes.bInheritHandle = true;
//Create mailslot.
HANDLE hSlot = CreateMailslotW(MAILSLOT_NAME, FILE_BUFFER_SIZE - 1U, MAILSLOT_WAIT_FOREVER, &SecurityAttributes);
if (hSlot == INVALID_HANDLE_VALUE)
{
LocalFree(SID_Value);
PrintError(LOG_LEVEL_2, LOG_ERROR_SYSTEM, L"Create mailslot error", GetLastError(), nullptr, 0);
return false;
}
ACL_Buffer.reset();
LocalFree(SID_Value);
//Initialization
std::shared_ptr<wchar_t> lpszBuffer(new wchar_t[FILE_BUFFER_SIZE]());
wmemset(lpszBuffer.get(), 0, FILE_BUFFER_SIZE);
DWORD cbMessage = 0;
BOOL Result = 0;
//MailSlot monitor
for (;;)
{
Sleep(LOOP_INTERVAL_TIME_NO_DELAY);
//Reset parameters.
wmemset(lpszBuffer.get(), 0, FILE_BUFFER_SIZE);
cbMessage = 0;
//Read message from mailslot.
Result = ReadFile(hSlot, lpszBuffer.get(), FILE_BUFFER_SIZE, &cbMessage, nullptr);
if (Result == FALSE)
{
PrintError(LOG_LEVEL_3, LOG_ERROR_SYSTEM, L"MailSlot read messages error", GetLastError(), nullptr, 0);
CloseHandle(hSlot);
return false;
}
else if (memcmp(lpszBuffer.get(), MAILSLOT_MESSAGE_FLUSH_DNS, sizeof(wchar_t) * wcslen(MAILSLOT_MESSAGE_FLUSH_DNS)) == 0)
{
FlushAllDNSCache();
}
else {
Sleep(LOOP_INTERVAL_TIME_MONITOR);
}
}
//Monitor terminated
CloseHandle(hSlot);
PrintError(LOG_LEVEL_2, LOG_ERROR_SYSTEM, L"MailSlot module Monitor terminated", 0, nullptr, 0);
return false;
}
示例15: main
int main(int argc, char* argv[]){
// Declare variables-------------------------------------------------------------
HashTable Index; // Inverted index
InitialiseHashTable(&Index);
char text[MAXLEN];
int test = 0;
// 1. Check input parameters--------------------------------------------------------
if (argc != 3 ){ // check number of arguments
fprintf(stderr,"Error: Incorrect number of input argument\n");
return -1;
}else if(!IsFile(argv[1])){ // check if file is valid
fprintf(stderr,"Error: File %s is invalid\n", argv[1]);
return -1;
}else if(!IsDir(argv[2])){ // check if directory is valid
fprintf(stderr,"Error: Directory %s cannot be found\n", argv[2]);
return -1;
}
// 2. Reconstruct Inverted Index-----------------------------------------------------
printf("Please wait while the query engine is loading. It might take a few minutes... \n");
if(!ReadFile(&Index, argv[1])){
CleanUpHash(&Index);
return -1;
}
// 3. Command Line interface and query -----------------------------------------------
for(int j=0; j<9; j++){
// Create text array for automated testing
switch (j){
case 0:
printf("\n3.%d Test invalid input syntax\n",j+1);
printf("QUERY :> AND dog\n");
strcpy(text,"AND dog\n");
break;
case 1:
printf("\n3.%d Test invalid input syntax\n", j+1);
printf("QUERY :> cat OR AND dog\n");
strcpy(text,"cat OR AND dog\n");
break;
case 2:
printf("\n3.%d Test no result\n", j+1);
printf("QUERY :> thisisrandom\n");
strcpy(text,"thisisrandom\n");
break;
case 3:
printf("\n3.%d Test single entry\n", j+1);
printf("QUERY :> incredible\n");
strcpy(text,"incredible\n");
break;
case 4:
printf("\n3.%d Test uppercase\n", j+1);
printf("QUERY :> Incredible\n");
strcpy(text,"Incredible\n");
break;
case 5:
printf("\n3.%d Test AND\n", j+1);
printf("QUERY :> Dartmouth AND College AND Computer AND Science\n");
strcpy(text,"Dartmouth AND College AND Computer AND Science\n");
break;
case 6:
printf("\n3.%d Test space as AND\n", j+1);
printf("QUERY :> Dartmouth College Computer Science\n");
strcpy(text,"Dartmouth College Computer Science\n");
break;
case 7:
printf("\n3.%d Test OR\n", j+1);
printf("QUERY :> Dartmouth OR Computer\n");
strcpy(text,"Dartmouth OR Computer\n");
break;
case 8:
printf("\n3.%d Test combined\n", j+1);
printf("QUERY :> Dartmouth College AND Hanlon OR Mathematics AND Computer Science AND Philosophy OR incredibles Pixar\n");
strcpy(text,"Dartmouth College AND Hanlon OR Mathematics AND Computer Science AND Philosophy OR incredibles Pixar\n");
break;
}
// a) declare variables
int unionflag, flag, size_temp, size_intersect, size_final, count;
char wordarray[MAXLEN][MAXLEN];
int temparray[MAXSIZE][2], intersect[MAXSIZE][2], final[MAXSIZE][2];
// b) instantiate variables
size_temp = size_intersect = size_final = unionflag = flag = 0;
count = StringToWord(wordarray,text);
// c) query
for(int i=0; i<count; i++){
if(i==0 && strcmp(wordarray[i],"AND") && strcmp(wordarray[i],"OR")){ // if it's the first word and is not invalid
NormalizeWord(wordarray[i]);
size_intersect = FindHash(wordarray[i], intersect, Index);
continue;
}else if(i==0){ // if it is first word and invalid
flag = 1; break;
}else if(unionflag){
if(strcmp(wordarray[i],"AND") && strcmp(wordarray[i],"OR")){
//.........这里部分代码省略.........