当前位置: 首页>>代码示例>>C++>>正文


C++ CreateFile函数代码示例

本文整理汇总了C++中CreateFile函数的典型用法代码示例。如果您正苦于以下问题:C++ CreateFile函数的具体用法?C++ CreateFile怎么用?C++ CreateFile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了CreateFile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: _splitpath

HRESULT CProteinSurfaceBase::CreateAdjacentVertex()
{
	char drive[_MAX_DRIVE];
	char dir[_MAX_DIR];
	char fname[_MAX_FNAME];
	char ext[_MAX_EXT];
	_splitpath(m_pPDB->m_strFilename, drive, dir, fname, ext );

	CString strSurfaceDir = GetMainApp()->m_strBaseSurfacePath;

	CString outputName;
	outputName.Format ( _T("%s%s_%02d_%c_%03d_%.2f_%d_%d_%d") , strSurfaceDir, fname, m_modelID, m_chainID, m_arrayAtom.size(), m_probeSphere, m_surfaceQuality, m_bAddHETATM, GetTypeGenSurface() );

	CString outputFilenameAdjacentVertex = outputName + _T(".Adjacent");

	BOOL bExistSurface = FALSE;
	HANDLE fileAdjacent = CreateFile( outputFilenameAdjacentVertex, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
	if( INVALID_HANDLE_VALUE != fileAdjacent )
	{
		bExistSurface = TRUE;
	}
	if ( fileAdjacent != INVALID_HANDLE_VALUE ) CloseHandle(fileAdjacent);

	BOOL bReadSuccess = FALSE;
	if ( bExistSurface == TRUE )
	{
		CFile fileAdjacentVertex;
		CFileException ex;
		if ( fileAdjacentVertex.Open(outputFilenameAdjacentVertex, CFile::modeRead, &ex) )
		{
			TCHAR buffHeader[512] = {0,};
			fileAdjacentVertex.Read(buffHeader, _tcslen(SURFACE_CURVATURE_HEADER));
			if ( CString(SURFACE_CURVATURE_HEADER) == CString(buffHeader) )
			{
				long numArray;
				fileAdjacentVertex.Read(&numArray, sizeof(long));

				m_ArrayArrayAdjacentVertex.clear();
				m_ArrayArrayAdjacentVertex.resize(numArray);

				long iProgress = GetMainActiveView()->InitProgress(100);
				for ( int i = 0 ; i < m_ArrayArrayAdjacentVertex.size(); i++ )
				{
					if ( i % (m_ArrayArrayAdjacentVertex.size()/100) == 0 )
						GetMainActiveView()->SetProgress(i*100/m_ArrayArrayAdjacentVertex.size(), iProgress);

					CSTLLONGArray & arrayAdjacentVertex = m_ArrayArrayAdjacentVertex[i];

					long numAdjacentVertex;
					fileAdjacentVertex.Read(&numAdjacentVertex, sizeof(long));
					arrayAdjacentVertex.resize(numAdjacentVertex);

					fileAdjacentVertex.Read(&arrayAdjacentVertex[0], sizeof(long)*numAdjacentVertex);
				}
				GetMainActiveView()->EndProgress(iProgress);

				fileAdjacentVertex.Close();

				if ( m_ArrayArrayAdjacentVertex.size() == i )
					bReadSuccess = TRUE;
			}
		}
	}

	if ( bReadSuccess == FALSE )
	{
		//	setArrayAdjacentVertex 를 구함
		m_ArrayArrayAdjacentVertex.clear();
		m_ArrayArrayAdjacentVertex.resize(m_arrayVertex.size());

		long iProgress = GetMainActiveView()->InitProgress(100);

		long deltaProgress = m_arrayIndexFace.size()/90;
		deltaProgress -= deltaProgress%3;

		//	
		for ( int i = 0 ; i < m_arrayIndexFace.size() ; i+=3 )
		{
			if ( deltaProgress && (i % deltaProgress == 0) )
				GetMainActiveView()->SetProgress(i*100/m_arrayIndexFace.size() , iProgress);

			long index1 = m_arrayIndexFace[i];
			long index2 = m_arrayIndexFace[i+1];
			long index3 = m_arrayIndexFace[i+2];

			if ( m_ArrayArrayAdjacentVertex[index1].capacity() == 0 )
				m_ArrayArrayAdjacentVertex[index1].reserve(20);
			if ( m_ArrayArrayAdjacentVertex[index2].capacity() == 0 )
				m_ArrayArrayAdjacentVertex[index2].reserve(20);
			if ( m_ArrayArrayAdjacentVertex[index3].capacity() == 0 )
				m_ArrayArrayAdjacentVertex[index3].reserve(20);

			m_ArrayArrayAdjacentVertex[index1].push_back(index2);
			m_ArrayArrayAdjacentVertex[index1].push_back(index3);

			m_ArrayArrayAdjacentVertex[index2].push_back(index1);
			m_ArrayArrayAdjacentVertex[index2].push_back(index3);

			m_ArrayArrayAdjacentVertex[index3].push_back(index1);
			m_ArrayArrayAdjacentVertex[index3].push_back(index2);
//.........这里部分代码省略.........
开发者ID:AnthonyNystrom,项目名称:GenXSource,代码行数:101,代码来源:ProteinSurfaceBase.cpp

示例2: CreateMRFromBMP

bool CreateMRFromBMP(const char *psFileName, char *ppbBuffer, int *pdwBufferSize)
{
	// Open the BMP file.
	HANDLE hFile = CreateFile(psFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		// Print error and return.
		printf("ERROR: failed to open file %s!\n", psFileName);
		return false;
	}

	// Get the size of the file.
	int dwFileSize = GetFileSize(hFile, NULL);

	// Allocate a buffer for the BMP file.
	BYTE *pbBmpBuffer = new BYTE[dwFileSize];

	// Read the BMP file into memory.
	DWORD Count = 0;
	ReadFile(hFile, pbBmpBuffer, dwFileSize, &Count, NULL);

	// Close the BMP file.
	CloseHandle(hFile);

	// Parse the BMP header and check if the magic is valid.
	BMPHeader *pBmpHeader = (BMPHeader*)pbBmpBuffer;
	if (pBmpHeader->wMagic != ByteFlip16(BMP_HEADER_MAGIC))
	{
		// Print an error and return.
		printf("ERROR: BMP image has invalid magic!\n");
		delete[] pbBmpBuffer;
		return false;
	}

	// Check the width and height are within range.
	if (pBmpHeader->sInfo.dwWidth > MR_MAX_WIDTH || pBmpHeader->sInfo.dwHeight > MR_MAX_HEIGHT)
	{
		// Print a warning and try to continue.
		printf("WARNING: bmp image has invalid resolution, should be 320x94 or smaller!, continuing anyway...\n");
	}

	// Check to make sure the bmp image is 32bbp.
	if (pBmpHeader->sInfo.wBitsPerPixel != 32)
	{
		printf("ERROR: bmp image should be 32bbp!\n");
		delete[] pbBmpBuffer;
		return false;
	}

	// Allocate a temp working buffer for the MR image.
	BYTE *pbMRTempBuffer = new BYTE[pBmpHeader->sInfo.dwWidth * pBmpHeader->sInfo.dwHeight * 4];
	memset(pbMRTempBuffer, 0, pBmpHeader->sInfo.dwWidth * pBmpHeader->sInfo.dwHeight * 4);

	// Create a MR image header.
	MRHeader *pMRHeader = (MRHeader*)pbMRTempBuffer;
	pMRHeader->wMagic = ByteFlip16(MR_IMAGE_MAGIC);
	pMRHeader->dwWidth = pBmpHeader->sInfo.dwWidth;
	pMRHeader->dwHeight = pBmpHeader->sInfo.dwHeight;

	// Create the color palette.
	int colors = 0;
	PaletteColor *pColorPalette = (PaletteColor*)&pbMRTempBuffer[sizeof(MRHeader)];

	// Create a pixel buffer for the image data.
	BYTE *pbMRPixelData = (BYTE*)&pbMRTempBuffer[sizeof(MRHeader) + (sizeof(PaletteColor) * 128)];
	DWORD *pdwBmpPixelData = (DWORD*)&pbBmpBuffer[pBmpHeader->dwDataOffset];

	// Loop through the pixel buffer and process each one.
	DWORD length = 0;
	for (int pos = 0; pos < pBmpHeader->sInfo.dwImageSize; )
	{
		// Determine the size of the pixel run.
		int run = 1;
		while ((pdwBmpPixelData[pos] == pdwBmpPixelData[pos + run]) && (run < 0x17f) &&
			(pos + run <= pBmpHeader->sInfo.dwImageSize))
		{
			// Pixel n is the same as the current pixel, so increase the run length by 1.
			run++;
		}

		// Check if this color is in the color palette and if not add it.
		int colorIndex = -1;
		for (int i = 0; i < colors; i++)
		{
			// Check if this color matches the current pixel.
			if (pdwBmpPixelData[pos] == pColorPalette[i].Color)
			{
				// Found the color, break the loop.
				colorIndex = i;
				break;
			}
		}

		// Check if we found the color in the color palette.
		if (colorIndex == -1)
		{
			// We did not find the color in the color palette, see if there is room to add it.
			if (colors < 128)
			{
				// Add the color to the palette.
//.........这里部分代码省略.........
开发者ID:grimdoomer,项目名称:SegaCDI,代码行数:101,代码来源:MRImage.cpp

示例3: LSLog

BOOL WINAPI LSLog(int nLevel, LPCSTR pszModule, LPCSTR pszMessage)
{
#if defined(LS_COMPAT_LOGGING)
    wchar_t wzLogFile[MAX_PATH] = { 0 };

    int nLogLevel = GetRCIntW(L"LSLogLevel", 2);

    // Should this message be logged?
    if (!pszModule || !pszMessage ||
        (nLevel > nLogLevel) || (nLevel < 1) || (nLevel > 4))
    {
        return FALSE;
    }

    // Has a log file been assigned?
    if (!GetRCStringW(L"LSLogFile", wzLogFile, NULL, MAX_PATH))
    {
        return FALSE;
    }

    // If so, open it
    HANDLE hLogFile = CreateFile(wzLogFile,
        GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    // Did open succeed?
    if (hLogFile == INVALID_HANDLE_VALUE)
    {
        return FALSE;
    }

    // Move to the end of the file
    SetFilePointer(hLogFile, 0, NULL, FILE_END);

    // Get timestamp
    SYSTEMTIME st = { 0 };
    GetLocalTime(&st);

    // Add timestamp and module name to message
    LPCSTR rszLevel[4] = { "Error", "Warning", "Notice", "Debug" };

    CHAR szLine[MAX_LINE_LENGTH] = { 0 };
    size_t cbLine = sizeof(szLine);
    size_t cbRemaining = 0;

    if (SUCCEEDED(StringCbPrintfExA(szLine, cbLine, NULL, &cbRemaining,
        STRSAFE_IGNORE_NULLS, "%02d-%02d-%04d %02d:%02d:%02d - %s - %s: %s\r\n",
        st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond,
        rszLevel[nLevel-1], pszModule, pszMessage)))
    {
        size_t cbToWrite = cbLine - cbRemaining;
        ASSERT(cbToWrite <= MAXDWORD);

        // Write it to the log file
        DWORD dwCount = 0;
        WriteFile(hLogFile, szLine, (DWORD)cbToWrite, &dwCount, NULL);
    }

    // Close the log
    CloseHandle(hLogFile);
#endif // LS_COMPAT_LOGGING

    return TRUE;
}
开发者ID:DamianSuess,项目名称:LiteStep,代码行数:68,代码来源:stubs.cpp

示例4: main


//.........这里部分代码省略.........
		static WCHAR buffer[BUFSIZE];
		allocate_console = 1;
		initialize_top_level_path(top_level_path, exepath, NULL, 1);

		/* set the default exe module */
		wcscpy(exe, top_level_path);
		swprintf(buffer, BUFSIZE, L"\"%s\"", top_level_path);
		PathAppend(exe, msystem_bin);
		PathAppend(exe, L"wish.exe");
		if (_waccess(exe, 0) != -1)
			PathAppend(buffer, msystem_bin);
		else {
			wcscpy(exe, top_level_path);
			PathAppend(exe, L"mingw\\bin\\wish.exe");
			PathAppend(buffer, L"mingw\\bin");
		}
		PathAppend(buffer, L"gitk");
		prefix_args = buffer;
		prefix_args_len = wcslen(buffer);
	}

	if (needs_env_setup) {
		if (!top_level_path[0])
			initialize_top_level_path(top_level_path, exepath,
					msystem_bin, -4);

		setup_environment(top_level_path, full_path);
	}
	cmd = fixup_commandline(exepath, &exep, &wait,
		prefix_args, prefix_args_len, is_git_command, skip_arguments);

	if (working_directory == (LPWSTR)1) {
		int len = GetEnvironmentVariable(L"HOME", NULL, 0);

		if (len) {
			working_directory = malloc(sizeof(WCHAR) * len);
			GetEnvironmentVariable(L"HOME", working_directory, len);
		}
	}

	{
		STARTUPINFO si;
		PROCESS_INFORMATION pi;
		DWORD creation_flags = CREATE_UNICODE_ENVIRONMENT;
		HANDLE console_handle;
		BOOL br = FALSE;
		ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
		ZeroMemory(&si, sizeof(STARTUPINFO));
		si.cb = sizeof(STARTUPINFO);

		if (allocate_console | show_console)
			creation_flags |= CREATE_NEW_CONSOLE;
		else if ((console_handle = CreateFile(L"CONOUT$", GENERIC_WRITE,
				FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
				FILE_ATTRIBUTE_NORMAL, NULL)) !=
				INVALID_HANDLE_VALUE)
			CloseHandle(console_handle);
		else {
#define STD_HANDLE(field, id) si.hStd##field = GetStdHandle(STD_##id); if (!si.hStd##field) si.hStd##field = INVALID_HANDLE_VALUE
			STD_HANDLE(Input, INPUT_HANDLE);
			STD_HANDLE(Output, OUTPUT_HANDLE);
			STD_HANDLE(Error, ERROR_HANDLE);
			si.dwFlags = STARTF_USESTDHANDLES;


			creation_flags |= CREATE_NO_WINDOW;
		}
		if (show_console) {
			si.dwFlags |= STARTF_USESHOWWINDOW;
			si.wShowWindow = SW_SHOW;
		}
		br = CreateProcess(/* module: null means use command line */
				exep,
				cmd,  /* modified command line */
				NULL, /* process handle inheritance */
				NULL, /* thread handle inheritance */
					/* handles inheritable? */
				allocate_console ? FALSE : TRUE,
				creation_flags,
				NULL, /* environment: use parent */
				working_directory, /* use parent's */
				&si, &pi);
		if (br) {
			if (wait)
				WaitForSingleObject(pi.hProcess, INFINITE);
			if (!GetExitCodeProcess(pi.hProcess, (DWORD *)&r))
				print_error(L"error reading exit code",
					GetLastError());
			CloseHandle(pi.hProcess);
		}
		else {
			print_error(L"error launching git", GetLastError());
			r = 1;
		}
	}

	free(cmd);

	ExitProcess(r);
}
开发者ID:DavidTongxx,项目名称:git,代码行数:101,代码来源:git-wrapper.c

示例5: main

int __cdecl main(int argc, char *argv[])
{
    HANDLE TheFile, WaitFile;
    int result = 0;
    char DataBuffer[BUF_SIZE];
    DWORD BytesRead;
    
    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }
    
    /* Open the same file that the parent has opened and locked */
    TheFile = CreateFile(FILENAME,     
                         GENERIC_READ|GENERIC_WRITE, 
                         FILE_SHARE_READ|FILE_SHARE_WRITE,
                         NULL,     
                         OPEN_EXISTING,                 
                         FILE_ATTRIBUTE_NORMAL, 
                         NULL);
    
    if (TheFile == INVALID_HANDLE_VALUE) 
    { 
        Trace("ERROR: Could not open file '%s' with CreateFile.",FILENAME); 
        result = 1;
    }
    
    /* Open up the WaitFile that we're using for IPC */
    WaitFile = CreateFile(WAITFILENAME,     
                          GENERIC_READ|GENERIC_WRITE, 
                          FILE_SHARE_READ|FILE_SHARE_WRITE,
                          NULL,                          
                          OPEN_ALWAYS,                 
                          FILE_ATTRIBUTE_NORMAL, 
                          NULL);
    
    if (WaitFile == INVALID_HANDLE_VALUE) 
    { 
        Trace("ERROR: Could not open file '%s' with CreateFile. "
             "GetLastError() returned %d.",WAITFILENAME,GetLastError()); 
        result = 1;
    }
    
    /* Lock the same file that the parent process locked, but the child
       locks bytes 11 through 20
    */

    if(LockFile(TheFile, 11, 0, 10, 0) == 0)
    {
        Trace("ERROR: LockFile failed in the child proccess.  "
              "GetLastError returns %d.",
              GetLastError());
        result = 1;
    }
    
    /* Check to ensure the parent lock is respected */
    if(ReadFile(TheFile, DataBuffer, 10, &BytesRead, NULL) != 0)
    {
        Trace("ERROR: ReadFile returned success when it should "
             "have failed.  Attempted to read the first 10 bytes "
             "of a file which was locked by the parent process.");
        result = 1;
    }

    /* Check to ensure the lock put on by this proccess doesn't restrict
       access
    */

    if(SetFilePointer(TheFile, 11, 0, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
    {
        Trace("ERROR: SetFilePointer was unable to move the file pointer to "
              "the 11th byte in the file, within the child proccess.  "
              "GetLastError() returned %d.",GetLastError());
        result = 1;
    }

    if(ReadFile(TheFile, DataBuffer, 10, &BytesRead, NULL) == 0)
    {
        Trace("ERROR: ReadFile failed when attempting to read a section of "
             "the file which was locked by the current process.  It should "
             "have been able to read this.  GetLastError() returned %d.",
             GetLastError());
        result = 1;
    }

    // Sleep for a bit to give the parent a chance to block before we do.
    Sleep(1000);

    /* Switch back to the parent, so it can check the child's locks */
    SignalAndBusyWait(WaitFile);

    if(UnlockFile(TheFile, 11, 0, 10, 0) == 0)
    {
        Fail("ERROR: Failed to Unlock bytes 11-20 in the file.  "
             "GetLastError returned %d.",GetLastError());
    }
    
    PAL_Terminate();
    return result;
}
开发者ID:smartmaster,项目名称:sscli,代码行数:100,代码来源:helper.c

示例6: MyDecryptFile

//-------------------------------------------------------------------
// Code for the function MyDecryptFile called by main.
//-------------------------------------------------------------------
// Parameters passed are:
//  pszSource, the name of the input file, an encrypted file.
//  pszDestination, the name of the output, a plaintext file to be 
//   created.
//  pszPassword, either NULL if a password is not to be used or the 
//   string that is the password.
bool MyDecryptFile(
    LPTSTR pszSourceFile, 
    LPTSTR pszDestinationFile, 
    LPTSTR pszPassword)
{ 
    //---------------------------------------------------------------
    // Declare and initialize local variables.
    bool fReturn = false;
    HANDLE hSourceFile = INVALID_HANDLE_VALUE;
    HANDLE hDestinationFile = INVALID_HANDLE_VALUE; 
    HCRYPTKEY hKey = NULL; 
    HCRYPTHASH hHash = NULL; 

    HCRYPTPROV hCryptProv = NULL; 

    DWORD dwCount;
    PBYTE pbBuffer = NULL; 
    DWORD dwBlockLen; 
    DWORD dwBufferLen; 

    //---------------------------------------------------------------
    // Open the source file. 
    hSourceFile = CreateFile(
        pszSourceFile, 
        FILE_READ_DATA,
        FILE_SHARE_READ,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    if(INVALID_HANDLE_VALUE != hSourceFile)
    {
        _tprintf(
            TEXT("The source encrypted file, %s, is open. \n"), 
            pszSourceFile);
    }
    else
    { 
        MyHandleError(
            TEXT("Error opening source plaintext file!\n"), 
            GetLastError());
        goto Exit_MyDecryptFile;
    } 

    //---------------------------------------------------------------
    // Open the destination file. 
    hDestinationFile = CreateFile(
        pszDestinationFile, 
        FILE_WRITE_DATA,
        FILE_SHARE_READ,
        NULL,
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);
    if(INVALID_HANDLE_VALUE != hDestinationFile)
    {
         _tprintf(
             TEXT("The destination file, %s, is open. \n"), 
             pszDestinationFile);
    }
    else
    {
        MyHandleError(
            TEXT("Error opening destination file!\n"), 
            GetLastError()); 
        goto Exit_MyDecryptFile;
    }

    //---------------------------------------------------------------
    // Get the handle to the default provider. 
    if(CryptAcquireContext(
        &hCryptProv, 
        NULL, 
        MS_ENH_RSA_AES_PROV, 
        PROV_RSA_AES, 
        0))
    {
        _tprintf(
            TEXT("A cryptographic provider has been acquired. \n"));
    }
    else
    {
        MyHandleError(
            TEXT("Error during CryptAcquireContext!\n"), 
            GetLastError());
        goto Exit_MyDecryptFile;
    }

    //---------------------------------------------------------------
    // Create the session key.
    if(!pszPassword || !pszPassword[0]) 
//.........这里部分代码省略.........
开发者ID:josh200501,项目名称:mycode_vs,代码行数:101,代码来源:main.cpp

示例7: IsAlphaNum

void
LoggerImpl::StartLogger(const NMEA_INFO &gps_info,
                    const SETTINGS_COMPUTER &settings,
                    const TCHAR *astrAssetNumber)
{
  HANDLE hFile;
  int i;
  TCHAR path[MAX_PATH];
  TCHAR cAsset[3];
  for (i=0; i < 3; i++) { // chars must be legal in file names
    cAsset[i] = IsAlphaNum(strAssetNumber[i]) ? strAssetNumber[i] : _T('A');
  }

// VENTA3 use logs subdirectory when not in main memory (true for FIVV and PNA)
#if defined(GNAV) || defined(FIVV) || defined(PNA)
  LocalPath(path,TEXT("logs"));
#else
  LocalPath(path);
#endif

  if (task.isTaskModified()) {
    task.SaveDefaultTask();
  }

#ifdef WINDOWSPC
  _stprintf(szLoggerFileName, TEXT("/tmp/tmp.IGC"));
#else
  _stprintf(szLoggerFileName, TEXT("\\tmp.IGC"));
#endif
  DeleteFile(szLoggerFileName);

  LoggerGInit();

  for(i=1;i<99;i++)
    {
      // 2003-12-31-XXX-987-01.IGC
      // long filename form of IGC file.
      // XXX represents manufacturer code

      if (!settings.LoggerShortName) {
        // Long file name
        _stprintf(szFLoggerFileName,
                 TEXT("%s\\%04d-%02d-%02d-XCS-%c%c%c-%02d.IGC"),
                 path,
                 gps_info.Year,
                 gps_info.Month,
                 gps_info.Day,
                 cAsset[0],
                 cAsset[1],
                 cAsset[2],
                 i);

        _stprintf(szFLoggerFileNameRoot,
                 TEXT("%s\\%04d-%02d-%02d-XCS-%c%c%c-%02d.IGC"),
                 TEXT(""), // this creates it in root if MoveFile() fails
                 gps_info.Year,
                 gps_info.Month,
                 gps_info.Day,
                 cAsset[0],
                 cAsset[1],
                 cAsset[2],
                 i);
      } else {
        // Short file name
        TCHAR cyear, cmonth, cday, cflight;
        cyear = NumToIGCChar((int)gps_info.Year % 10);
        cmonth = NumToIGCChar(gps_info.Month);
        cday = NumToIGCChar(gps_info.Day);
        cflight = NumToIGCChar(i);
        _stprintf(szFLoggerFileName,
                 TEXT("%s\\%c%c%cX%c%c%c%c.IGC"),
                 path,
                 cyear,
                 cmonth,
                 cday,
                 cAsset[0],
                 cAsset[1],
                 cAsset[2],
                 cflight);

        _stprintf(szFLoggerFileNameRoot,
                 TEXT("%s\\%c%c%cX%c%c%c%c.IGC"),
                 TEXT(""), // this creates it in root if MoveFile() fails
                 cyear,
                 cmonth,
                 cday,
                 cAsset[0],
                 cAsset[1],
                 cAsset[2],
                 cflight);
      } // end if

      hFile = CreateFile(szFLoggerFileName, GENERIC_WRITE,
			 FILE_SHARE_WRITE, NULL, CREATE_NEW,
			 FILE_ATTRIBUTE_NORMAL, 0);
      if(hFile!=INVALID_HANDLE_VALUE )
	{
          // file already exists
      CloseHandle(hFile);
      DeleteFile(szFLoggerFileName);
//.........这里部分代码省略.........
开发者ID:scottp,项目名称:xcsoar,代码行数:101,代码来源:LoggerImpl.cpp

示例8: main

int
main(int argc, char **argv)
{
    char **av = argv;
    struct sockaddr_in host;
    register afs_int32 code;
    extern struct hostent *gethostbyname();
    struct hostent *hp;
    char *hostname;
    char hnamebuf[200];
    struct timeval tv;
    int noAuth = 1;		/* Default is authenticated connections */

    argc--, av++;
    if (argc < 1) {
	printf("usage: pxclient <serverHost>\n");
	exit(1);
    }
    memset((char *)&host, 0, sizeof(struct sockaddr_in));
    host.sin_family = AF_INET;
    host.sin_addr.s_addr = inet_addr(av[0]);
#ifdef STRUCT_SOCKADDR_HAS_SA_LEN
    host.sin_len = sizeof(struct sockaddr_in);
#endif
    if (host.sin_addr.s_addr != -1) {
	strcpy(hnamebuf, av[0]);
	hostname = hnamebuf;
    } else {
	hp = gethostbyname(av[0]);
	if (hp) {
	    host.sin_family = hp->h_addrtype;
	    memcpy((caddr_t) & host.sin_addr, hp->h_addr, hp->h_length);
	    hostname = hp->h_name;
	} else {
	    printf("unknown server host %s\n", av[0]);
	    exit(1);
	}
    }
    if ((code = pxclient_Initialize(noAuth, host.sin_addr.s_addr)) != 0) {
	printf("Couldn't initialize fs library (code=%d).\n", code);
	exit(1);
    }

    code = ubik_Call(RXAFS_GetTime, cstruct, 0, &tv.tv_sec, &tv.tv_usec);
    if (!code)
	printf("AFS_GetTime on %s sec=%ld, usec=%ld\n", av[0], tv.tv_sec,
	       tv.tv_usec);
    else
	printf("return code is %d\n", code);

#ifdef notdef
    while (1) {
	char line[500];
	int nargs;

	printf("fs> ");
	if (fgets(line, 499, stdin) != NULL) {
	    char *oper;
	    register char **argp = args;
	    GetArgs(line, argp, &nargs);
	    oper = &argp[0][0];
	    ++argp, --nargs;
	    if (!strcmp(oper, "probe")) {
		code =
		    ubik_Call(RXAFS_GetTime, cstruct, 0, &tv.tv_sec,
			      &tv.tv_usec);
		printf("return code is %d\n", code);
		if (!code)
		    printf("sec=%d\n", tv.tv_sec);
	    } else if (!strcmp(oper, "fsstats")) {
		struct afsStatistics stats;

		code = ubik_AFS_GetStatistics(cstruct, 0, &stats);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "fd")) {
		code = FetchData(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "fs")) {
		code = FetchStatus(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "fa")) {
		code = FetchACL(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "sd")) {
		code = StoreData(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "ss")) {
		code = StoreStatus(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "sa")) {
		code = StoreACL(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "cf")) {
		code = CreateFile(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "rf")) {
		code = RemoveFile(argp);
		printf("return code is %d\n", code);
	    } else if (!strcmp(oper, "rn")) {
		code = Rename(argp);
//.........这里部分代码省略.........
开发者ID:maxendpoint,项目名称:openafs_cvs,代码行数:101,代码来源:fsprobe.c

示例9: ATLTRACE2


//.........这里部分代码省略.........
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgLogin = RegisterWindowMessage( L"Login" );

   if(0 == m_msgLogin)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgAuthenticate = RegisterWindowMessage( L"Authenticate" );

   if(0 == m_msgAuthenticate)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgLogout = RegisterWindowMessage( L"Logout" );

   if(0 == m_msgLogout)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgVerifyPermission = RegisterWindowMessage( L"VerifyPermission" );

   if(0 == m_msgVerifyPermission)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgSendMessage = RegisterWindowMessage( L"SendMessage" );

   if(0 == m_msgSendMessage)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgGetListContents = RegisterWindowMessage( L"GetListContents" );

   if(0 == m_msgGetListContents)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   m_msgExitMessageLoop = RegisterWindowMessage( L"ExitMessageLoop" );

   if(0 == m_msgExitMessageLoop)
   {
      hr = HRESULT_FROM_WIN32(GetLastError());
      ATLTRACE2("FinalConstruct: RegisterWindowMessage failed. %x\n", hr);
      goto cleanup;
   }

   hr = this->CreateCredentialsFilePath();

   if(FAILED(hr))
   {
      ATLTRACE2("FinalConstruct: CreateCredentialsFilePath failed. %x\n", hr);
      goto cleanup;
   }

   // Determine whether we have cached credentials.

   HANDLE hInfoFile = INVALID_HANDLE_VALUE;

   hInfoFile = CreateFile(
      g.credentialsFile,
      0,
      0,
      NULL,
      OPEN_EXISTING,
      FILE_ATTRIBUTE_NORMAL,
      NULL);

   if(INVALID_HANDLE_VALUE != hInfoFile)
   {
      // The file exists.
      // We have cached credentials.
      g.haveCachedCredentials = 1;
   }
    
   CloseHandle(hInfoFile);

cleanup:
   return hr;
}
开发者ID:Essjay1,项目名称:Windows-classic-samples,代码行数:101,代码来源:sample.cpp

示例10: CSourceStream

CPushPinBitmapSet::CPushPinBitmapSet(HRESULT *phr, CSource *pFilter)
      : CSourceStream(NAME("Push Source BitmapSet"), phr, pFilter, L"Out"),
        m_FramesWritten(0),
        m_bZeroMemory(0),
        m_iFrameNumber(0),
        m_rtFrameLength(FPS_2), // Display 2 bitmap frames per second
        m_iCurrentBitmap(0),
        m_bFilesLoaded(FALSE)
{
    int nFilesLoaded=0;

    // Initialize member data arrays
    ZeroMemory(&m_cbBitmapInfo, NUM_FILES * sizeof(DWORD));
    ZeroMemory(&m_pBmi,   NUM_FILES * sizeof(BITMAPINFO *));
    ZeroMemory(&m_hFile,  NUM_FILES * sizeof(HANDLE));
    ZeroMemory(&m_pFile,  NUM_FILES * sizeof(BYTE *));
    ZeroMemory(&m_pImage, NUM_FILES * sizeof(BYTE *));

    // The main point of this sample is to demonstrate how to take a DIB
    // in host memory and insert it into a video stream. 
    // We read a set of bitmaps from files and copy one bitmap
    // into every frame that we send downstream.

    // In the filter graph, we connect this filter to the AVI Mux, which creates 
    // the AVI file with the video frames we pass to it. In this case, 
    // the end result is a rotating set of images rendered as a video stream.    

    // Read the current directory and SDK media directory into local strings
    TCHAR szCurrentDir[MAX_PATH], szMediaDir[MAX_PATH];
    GetCurrentDirectory(MAX_PATH-1, szCurrentDir);
    lstrcpyn(szMediaDir, DXUtil_GetDXSDKMediaPath(), MAX_PATH-1);

    for (int i=0; i < NUM_FILES; i++)
    {
        TCHAR szFileCurrent[MAX_PATH], szFileMedia[MAX_PATH];

        // Assume that the bitmap in the application's directory
        wsprintf(szFileCurrent, TEXT("%s\\BitmapSet%d.bmp\0"), szCurrentDir, i);

        m_hFile[i] = CreateFile(szFileCurrent, GENERIC_READ, 0, NULL, OPEN_EXISTING,
                                FILE_ATTRIBUTE_NORMAL, NULL);

        if (m_hFile[i] == INVALID_HANDLE_VALUE)
        {
            // File was not in the application's current directory,
            // so look in the DirectX SDK media path instead.  The path contained
            // in szMediaDir will already have a trailing backslash '\'.
            wsprintf(szFileMedia, TEXT("%sBitmapSet%d.bmp\0"), szMediaDir, i);

            m_hFile[i] = CreateFile(szFileMedia, GENERIC_READ, 0, NULL, OPEN_EXISTING, 
                                    FILE_ATTRIBUTE_NORMAL, NULL);

            if (m_hFile[i] == INVALID_HANDLE_VALUE)
            {
                TCHAR szMsg[2*MAX_PATH + 100];

                wsprintf(szMsg, TEXT("Could not open bitmap source file (#%d of %d) in the application directory:\r\n\r\n\t[%s]\n\n")
                         TEXT("or in the DirectX SDK Media folder:\r\n\r\n\t[%s]\n\n")
                         TEXT("Please copy this file either to the application's folder\r\n")
                         TEXT("or to the DirectX SDK Media folder, then recreate this filter.\r\n")
                         TEXT("Otherwise, you will not be able to render the output pin.\0"),
                         i+1, NUM_FILES, szFileCurrent, szFileMedia);

                OutputDebugString(szMsg);
                MessageBox(NULL, szMsg, TEXT("PushSource filter error"), MB_ICONERROR | MB_OK);
                *phr = HRESULT_FROM_WIN32(GetLastError());
                return;
            }
        }

        DWORD dwFileSize = GetFileSize(m_hFile[i], NULL);
        if (dwFileSize == INVALID_FILE_SIZE)
        {
            DbgLog((LOG_TRACE, 1, TEXT("Invalid file size")));
            *phr = HRESULT_FROM_WIN32(GetLastError());
            return;
        }

        m_pFile[i] = new BYTE[dwFileSize];
        if(!m_pFile[i])
        {
            OutputDebugString(TEXT("Could not allocate m_pImage\n"));
            *phr = E_OUTOFMEMORY;
            return;
        }

        DWORD nBytesRead = 0;
        if(!ReadFile(m_hFile[i], m_pFile[i], dwFileSize, &nBytesRead, NULL))
        {
            *phr = HRESULT_FROM_WIN32(GetLastError());
            OutputDebugString(TEXT("ReadFile failed\n"));
            return;
        }

        // WARNING - This code does not verify the file is a valid bitmap file.
        // In your own filter, you would check this or else generate the bitmaps 
        // yourself in memory.

        int cbFileHeader = sizeof(BITMAPFILEHEADER);

//.........这里部分代码省略.........
开发者ID:chinajeffery,项目名称:dx_sdk,代码行数:101,代码来源:PushSourceBitmapSet.cpp

示例11: handle_file

/* handle_file: Open, get the fileno, seek to the end and update mtime */
int handle_file(int i, int do_fseek, int do_log)
{
    int fd;
    struct stat stat_fd;
    
    /* We must be able to open the file, fseek and get the
     * time of change from it.
     */
    #ifndef WIN32
    logff[i].fp = fopen(logff[i].file, "r");
    if(!logff[i].fp)
    {
        if(do_log == 1)
        {
            merror(FOPEN_ERROR, ARGV0, logff[i].file);
        }
        return(-1);
    }
    /* Getting inode number for fp */
    fd = fileno(logff[i].fp);
    if(fstat(fd, &stat_fd) == -1)
    {
        merror(FILE_ERROR,ARGV0,logff[i].file);
        fclose(logff[i].fp);
        logff[i].fp = NULL;
        return(-1);
    }
    
    logff[i].fd = stat_fd.st_ino;
    logff[i].size =  stat_fd.st_size;
    

    #else
    BY_HANDLE_FILE_INFORMATION lpFileInformation;

    logff[i].fp = NULL;
    logff[i].h = CreateFile(logff[i].file, GENERIC_READ,
                            FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE,
                            NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if(logff[i].h == INVALID_HANDLE_VALUE)
    {
        if(do_log == 1)
        {
            merror(FOPEN_ERROR, ARGV0, logff[i].file);
        }
        return(-1);
    }
    fd = _open_osfhandle((long)logff[i].h, 0);
    if(fd == -1)
    {
        merror(FOPEN_ERROR, ARGV0, logff[i].file);
        CloseHandle(logff[i].h);
        return(-1);
    }
    logff[i].fp = _fdopen(fd, "r");
    if(logff[i].fp == NULL)
    {
        merror(FOPEN_ERROR, ARGV0, logff[i].file);
        CloseHandle(logff[i].h);
        return(-1);
    }


    /* On windows, we also need the real inode, which is the combination
     * of the index low + index high numbers.
     */
    if(GetFileInformationByHandle(logff[i].h, &lpFileInformation) == 0)
    {
        merror("%s: Unable to get file information by handle.", ARGV0);
        fclose(logff[i].fp);
        CloseHandle(logff[i].h);
        logff[i].fp = NULL;
        return(-1);
    }

    logff[i].fd = (lpFileInformation.nFileIndexLow + lpFileInformation.nFileIndexHigh);
    logff[i].size = (lpFileInformation.nFileSizeHigh + lpFileInformation.nFileSizeLow);

    #endif


    /* Only seek the end of the file if set to. */
    if(do_fseek == 1 && S_ISREG(stat_fd.st_mode))
    {
        /* Windows and fseek causes some weird issues.. */
        #ifndef WIN32
        if(fseek(logff[i].fp, 0, SEEK_END) < 0)
        {
            merror(FSEEK_ERROR, ARGV0,logff[i].file);
            fclose(logff[i].fp);
            logff[i].fp = NULL;
            return(-1);
        }
        #endif
    }
    

    /* Setting ignore to zero */
    logff[i].ign = 0;
//.........这里部分代码省略.........
开发者ID:alexoslabs,项目名称:ossec-hids,代码行数:101,代码来源:logcollector.c

示例12: LogCollectorStart


//.........这里部分代码省略.........
                        CloseHandle(logff[i].h);
                        #endif
                    }
                    logff[i].fp = NULL;
                    handle_file(i, 0, 1);
                    continue;
                }

                /* Variable file name */
                else if(!logff[i].fp)
                {
                    handle_file(i, 0, 0);
                    continue;
                }
            }
            
            
            /* Check for file change -- if the file is open already */
            if(logff[i].fp)
            {
                #ifndef WIN32
                if(stat(logff[i].file, &tmp_stat) == -1)
                {
                    fclose(logff[i].fp);
                    logff[i].fp = NULL;
                    
                    merror(FILE_ERROR, ARGV0, logff[i].file);
                }

                #else
                BY_HANDLE_FILE_INFORMATION lpFileInformation;
                HANDLE h1;

                h1 = CreateFile(logff[i].file, GENERIC_READ,
                            FILE_SHARE_DELETE|FILE_SHARE_READ|FILE_SHARE_WRITE,
                            NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
                if(h1 == INVALID_HANDLE_VALUE)
                {
                    fclose(logff[i].fp);
                    CloseHandle(logff[i].h);
                    logff[i].fp = NULL;
                    merror(FILE_ERROR, ARGV0, logff[i].file);
                }
                else if(GetFileInformationByHandle(h1, &lpFileInformation) == 0)
                {
                    fclose(logff[i].fp);
                    CloseHandle(logff[i].h);
                    CloseHandle(h1);
                    logff[i].fp = NULL;
                    merror(FILE_ERROR, ARGV0, logff[i].file);;
                }
                #endif


                #ifdef WIN32
                else if(logff[i].fd != (lpFileInformation.nFileIndexLow + lpFileInformation.nFileIndexHigh))
                #else
                else if(logff[i].fd != tmp_stat.st_ino)
                #endif
                {
                    char msg_alert[512 +1];

                    snprintf(msg_alert, 512, "ossec: File rotated (inode "
                                             "changed): '%s'.",
                                             logff[i].file);
                     
开发者ID:alexoslabs,项目名称:ossec-hids,代码行数:66,代码来源:logcollector.c

示例13: EnumIpDataLines

static int EnumIpDataLines(const char *pszFileCSV,const char *pszFileOut)
{
	FILE *fp;
	char line[1024],out[512],*pszFrom,*pszTo,*pszTwo,*pszCountry,*buf;
	int i,j;
	DWORD dwOut;
	WORD wOut;
	struct ResizableByteBuffer buffer;

	memset(&buffer, 0, sizeof(buffer));
	fp=fopen(pszFileCSV,"rt");
	if (fp != NULL) {
		OutputDebugStringA("Running IP data convert...\n"); /* all ascii */
		while (!feof(fp)) {
			if (fgets(line,sizeof(line),fp) == NULL) break;
			/* get line data */
			pszFrom=line+1;
			pszTo=strchr(pszFrom,',');
			*(pszTo-1)='\0'; pszTo+=2;
			pszTwo=strchr(pszTo,',');
			*(pszTwo-1)='\0'; pszTwo+=2;
			pszCountry=strchr(pszTwo,',')+1;
			pszCountry=strchr(pszCountry,',')+2;
			buf=strchr(pszCountry,'"');
			*buf=pszTwo[2]='\0';
			/* corrections */
			if (!mir_tstrcmpi(pszCountry,"ANTARCTICA")) continue;
			if (!mir_tstrcmpi(pszCountry,"TIMOR-LESTE")) continue;
			if (!mir_tstrcmpi(pszCountry,"PALESTINIAN TERRITORY, OCCUPIED"))
				mir_tstrcpy(pszCountry,"ISRAEL");
			else if (!mir_tstrcmpi(pszCountry,"UNITED STATES MINOR OUTLYING ISLANDS"))
				mir_tstrcpy(pszCountry,"UNITED STATES");
			else if (!mir_tstrcmpi(pszCountry,"SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS"))
				mir_tstrcpy(pszCountry,"UNITED KINGDOM");
			else if (!mir_tstrcmpi(pszTwo,"JE")) /* map error */
				mir_tstrcpy(pszCountry,"UNITED KINGDOM");
			else if (!mir_tstrcmpi(pszTwo,"AX")) /* Åland Island belongs to Finland */
				mir_tstrcpy(pszCountry,"FINLAND");
			else if (!mir_tstrcmpi(pszTwo,"ME"))
				mir_tstrcpy(pszCountry,"MONTENEGRO");
			else if (!mir_tstrcmpi(pszTwo,"RS") || !mir_tstrcmpi(pszTwo,"CS"))
				mir_tstrcpy(pszCountry,"SERBIA");
			/* convert */
			for(i=0;i<nCountriesCount;i++) {
				/* map different writings */
				for(j=0;j<_countof(differentCountryNames);j++)
					if (!mir_tstrcmpi(countries[i].szName,differentCountryNames[j].szMir)) {
						buf=(char*)differentCountryNames[j].szCSV;
						break;
					}
				if (j == _countof(differentCountryNames))
					buf=(char*)countries[i].szName;
				/* check country */
				if (!mir_strcmpi(pszCountry,buf)) {
					dwOut=(DWORD)atoi(pszFrom);
					AppendToByteBuffer(&buffer,(void*)&dwOut,sizeof(DWORD));
					dwOut=(DWORD)atoi(pszTo);
					AppendToByteBuffer(&buffer,(void*)&dwOut,sizeof(DWORD));
					wOut=(WORD)countries[i].id;
					AppendToByteBuffer(&buffer,(void*)&wOut,sizeof(WORD));
					break;
				}
			}
			/* not in list */
			if (i == nCountriesCount) {
				mir_snprintf(out, _countof(out), "Unknown: %s-%s [%s, %s]\n", pszFrom, pszTo, pszTwo, pszCountry);
				OutputDebugStringA(out); /* all ascii */
			}
		}
		fclose(fp);
		OutputDebugStringA("Done!\n"); /* all ascii */
		if (buffer.buf != NULL) {
			HANDLE hFileOut;
			DWORD cbWritten=0;
			BYTE *compressed;
			DWORD cbCompressed;
			/* compress whole data */
			OutputDebugStringA("Compressing...\n"); /* all ascii */
			compressed=(BYTE*)mir_alloc(buffer.cbAlloced+384);
			if (compressed != NULL) {
				cbCompressed=Huffman_Compress(buffer.buf,compressed,buffer.cbLength);
				OutputDebugStringA("Done!\n"); /* all ascii */
				OutputDebugStringA("Writing to file...\n"); /* all ascii */
				hFileOut=CreateFile(pszFileOut,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
				if (hFileOut != INVALID_HANDLE_VALUE) {
					/* store data length count at beginning */
					dwOut=buffer.cbLength;
					WriteFile(hFileOut,&dwOut,sizeof(DWORD),&cbWritten,NULL);
					/* store compressed data records */
					WriteFile(hFileOut,compressed,cbCompressed,&cbWritten,NULL);
					CloseHandle(hFileOut);
				}
				OutputDebugStringA("Done!\n"); /* all ascii */
				mir_free(compressed);
			}
			mir_free(buffer.buf);
		}
		return 0;
	}
	return 1;
//.........这里部分代码省略.........
开发者ID:kmdtukl,项目名称:miranda-ng,代码行数:101,代码来源:ip2country.cpp

示例14: MyCrashHandlerExceptionFilter

static LONG __stdcall MyCrashHandlerExceptionFilter(EXCEPTION_POINTERS* pEx) 
{
#ifdef _M_IX86 
  if (pEx->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW)   
  { 
    // be sure that we have enought space... 
    static char MyStack[1024*128];   
    // it assumes that DS and SS are the same!!! (this is the case for Win32) 
    // change the stack only if the selectors are the same (this is the case for Win32) 
    //__asm push offset MyStack[1024*128]; 
    //__asm pop esp; 
    __asm mov eax,offset MyStack[1024*128]; 
    __asm mov esp,eax; 
  } 
#endif 
  MyStackWalker sw;
  sw.ShowCallstack(GetCurrentThread(), pEx->ContextRecord);
  Base::Console().Log("*** Unhandled Exception!\n");
  Base::Console().Log("   ExpCode: 0x%8.8X\n", pEx->ExceptionRecord->ExceptionCode);
  Base::Console().Log("   ExpFlags: %d\n", pEx->ExceptionRecord->ExceptionFlags);
  Base::Console().Log("   ExpAddress: 0x%8.8X\n", pEx->ExceptionRecord->ExceptionAddress);

  bool bFailed = true; 
  HANDLE hFile; 
  hFile = CreateFile(s_szMiniDumpFileName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 
  if (hFile != INVALID_HANDLE_VALUE) 
  { 
    MINIDUMP_EXCEPTION_INFORMATION stMDEI; 
    stMDEI.ThreadId = GetCurrentThreadId(); 
    stMDEI.ExceptionPointers = pEx; 
    stMDEI.ClientPointers = true; 
    // try to create an miniDump: 
    if (s_pMDWD( 
      GetCurrentProcess(), 
      GetCurrentProcessId(), 
      hFile, 
      s_dumpTyp, 
      &stMDEI, 
      NULL, 
      NULL 
      )) 
    { 
      bFailed = false;  // suceeded 
    } 
    CloseHandle(hFile); 
  } 

  if (bFailed) 
  { 
    return EXCEPTION_CONTINUE_SEARCH; 
  } 

  // Optional display an error message 
  // FatalAppExit(-1, ("Application failed!")); 


  // or return one of the following: 
  // - EXCEPTION_CONTINUE_SEARCH 
  // - EXCEPTION_CONTINUE_EXECUTION 
  // - EXCEPTION_EXECUTE_HANDLER 
  return EXCEPTION_CONTINUE_SEARCH;  // this will trigger the "normal" OS error-dialog 
} 
开发者ID:3DPrinterGuy,项目名称:FreeCAD,代码行数:62,代码来源:MainGui.cpp

示例15: stress_main

/*
 * ======================================================================= *
 * In the startup of this program, we look at our executable name and      *
 * replace the ".EXE" with ".DLL" to find the ISAPI DLL we need to load.   *
 * This means that the executable need only be given the same "name" as    *
 * the DLL to load. There is no recompilation required.                    *
 * ======================================================================= *
*/
BOOL stress_main(const char *filename, 
				const char *arg, 
				const char *postdata,
				const char *matchdata) 
{

	EXTENSION_CONTROL_BLOCK ECB;
	DWORD rc;
	TIsapiContext context;

	// open output and input files
	context.tid = GetCurrentThreadId();
	CString fname;
	fname.Format("%08X.out", context.tid);

	context.out = CreateFile(fname, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
	if (context.out==INVALID_HANDLE_VALUE) {
		printf("failed to open output file %s\n", fname);
		return 0;
	}

	// not using post files
	context.in = INVALID_HANDLE_VALUE;

	//
	// Fill the ECB with the necessary information
	//
	if (!FillExtensionControlBlock(&ECB, &context) ) {
		fprintf(stderr,"Fill Ext Block Failed\n");
		return -1;
	}
	
	// check for command line argument, 
	// first arg = filename
	// this is added for testing php from command line

	context.env.RemoveAll();
	context.env["PATH_TRANSLATED"]= filename;
	context.env["SCRIPT_MAP"]= filename;
	context.env["CONTENT_TYPE"]= "";
	context.env["CONTENT_LENGTH"]= "";
	context.env["QUERY_STRING"]= arg;
	context.env["METHOD"]="GET";
	context.env["PATH_INFO"] = "";
	context.waitEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
	char buf[MAX_PATH];
	if (postdata && *postdata !=0) {
		ECB.cbAvailable = strlen(postdata);
		ECB.cbTotalBytes = ECB.cbAvailable;
		ECB.lpbData = (unsigned char *)postdata;
		context.env["METHOD"]="POST";

		_snprintf(buf, sizeof(buf)-1, "%d", ECB.cbTotalBytes);
		context.env["CONTENT_LENGTH"]=buf;

		context.env["CONTENT_TYPE"]="application/x-www-form-urlencoded";
	}
	ECB.lpszMethod = strdup(context.env["METHOD"]);
    ECB.lpszPathTranslated = strdup(filename);
	ECB.lpszQueryString = strdup(arg);
	ECB.lpszPathInfo = strdup(context.env["PATH_INFO"]);


	// Call the DLL
	//
	rc = IsapiHttpExtensionProc(&ECB);
	if (rc == HSE_STATUS_PENDING) {
		// We will exit in ServerSupportFunction
		WaitForSingleObject(context.waitEvent, INFINITE);
	}
	CloseHandle(context.waitEvent);
	//Sleep(75);
	free(ECB.lpszPathTranslated);
	free(ECB.lpszQueryString);
	free(ECB.lpszMethod);
	free(ECB.lpszPathInfo);

	BOOL ok = TRUE;

	if (context.out != INVALID_HANDLE_VALUE) CloseHandle(context.out);

	// compare the output with the EXPECT section
	if (matchdata && *matchdata != 0) {
		ok = CompareFiles(fname, matchdata);
	}

	DeleteFile(fname);

	return ok;
		
}
开发者ID:kennyb,项目名称:php-broken,代码行数:99,代码来源:stresstest.cpp


注:本文中的CreateFile函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。