⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stdiol.c

📁 ISO 8583 with c++ for financial transaction standard
💻 C
📖 第 1 页 / 共 2 页
字号:
/* Estructura de mapeo de a 4 bits, hasta un total de 16 bits. */
typedef struct int16bitmap_tag
{
	bit_basetype first_low4bits  : 4;	/* bits 12 a 15 */
	bit_basetype secnd_low4bits  : 4;	/* bits  8 a 11 */
	bit_basetype first_high4bits : 4;	/* bits  4 a  7 */
	bit_basetype secnd_high4bits : 4;	/* bits  0 a  3 */
} int16bitmap_t;
typedef struct int16bitmap_tag *int16bitmap_ptr;
/********************************************************************************/

/*******************************************
 * de hexa a binario (destiny,source) 
 * char * : buffer binario
 * char * : buffer hexadecimal
 * int    : longitud de buffer hexadecimal
 ******************************************/
int EXPORT_ATTR hexcharbinary(short *binbuffer, char *hexbuffer, int iHexLen)
{
	 int				j, max;
	 unsigned char		byte1, byte2;
	 int16bitmap_ptr	ptr_int = (int16bitmap_ptr)binbuffer;

	/* precondicion */
	if(iHexLen < 0 || (iHexLen % 2) != 0 )
		return (0);
	/* maximo de buffer de a 16 bits */
	max = iHexLen / 2;
	/* de hexa a binario byte a byte */
	for(j=0; j < max; j++)
		{
		/* asegurar la linealialidad del rango {0..9,A..F} */
		if(hexbuffer[j*2] >= 'A' && hexbuffer[j*2] <= 'F')
			byte1 = '9' + (hexbuffer[j*2] - 'A') + 1;
		else if(hexbuffer[j*2] >= '0' && hexbuffer[j*2] <= '9')
			byte1 = hexbuffer[j*2];
		else
			return (-1);
		/* asegurar la linealialidad del rango {0..9,A..F} */
		if(hexbuffer[(j*2)+1] >= 'A' && hexbuffer[(j*2)+1] <= 'F')
			byte2 = '9' + (hexbuffer[(j*2)+1] - 'A') + 1;
		else if(hexbuffer[(j*2)+1] >= '0' && hexbuffer[(j*2)+1] <= '9')
			byte2 = hexbuffer[(j*2)+1];
		else
			return (-1);
		/* 2 bytes hexa empaquetados en 1 byte binario */
		if((j % 2) == 0)
			{
		       ptr_int->secnd_high4bits = (byte1 - '0');
		       ptr_int->first_high4bits = (byte2 - '0');
			}
		else
			{
			   ptr_int->secnd_low4bits = (byte1 - '0');
		       ptr_int->first_low4bits = (byte2 - '0');
			   /* cada 4 digitos hexa (16 bits) incrementar ptr entero */
			   ptr_int++;
			};
		};
	/* ok */
	return max;
};

/* de binario a hexa (destiny,source)      */
/* char * : buffer binario                 */
/* char * : buffer hexadecimal             */
/* int    : longitud de buffer hexadecimal */
int EXPORT_ATTR binaryhexchar(char *hexbuffer, int iHexLen, short *binbuffer)
{
	 int				j, max;
	 unsigned char		byte1, byte2;
	 int16bitmap_ptr	ptr_int = (int16bitmap_ptr)binbuffer;

	/* precondicion */
	if(iHexLen < 0 || (iHexLen % 2) != 0 )
		return (0);
	/* maximo de buffer de a 16 bits */
	max = iHexLen / 2;
	/* de binario a hexa byte a byte */
	for(j=0; j < max; j++)
		{
		/* 2 bytes hexa empaquetados en 1 byte binario */
		if((j % 2) == 0)
			{
		       byte1 = ptr_int->secnd_high4bits + '0';
		       byte2 = ptr_int->first_high4bits + '0';
			}
		else
			{
			   byte1 = ptr_int->secnd_low4bits + '0';
		       byte2 = ptr_int->first_low4bits + '0';
			   /* cada 4 digitos hexa (16 bits) incrementar ptr entero */
			   ptr_int++;
			};
		/* asegurar la linealialidad del rango {0..9,A..F} */
		if(byte1 >= ':' && byte1 <= '?')
			byte1 = 'A' + (byte1 - ':');
		else if (!(byte1 >= '0' && byte1 <= '9'))
			return (-1);
		if(byte2 >= ':' && byte2 <= '?')
			byte2 = 'A' + (byte2 - ':');
		else if (!(byte2 >= '0' && byte2 <= '9'))
			return (-1);
		hexbuffer[j*2]     = byte1;
		hexbuffer[(j*2)+1] = byte2;
		};
	/* ok */
	return max;
};

/******************************/
#endif /* _LITTLE_ENDIAN_BIT_ */
/******************************/


/* Macro de control del uso de nombre temporal */
#define _USE_TMP_FILENAME_

/********************************************************************/
/* Funcion de transferencia de archivo mediante servicio de FTP del */
/* Sistema Operativo                                                */
/********************************************************************/
int ftp_send_file(char *szHost,char *szUser, char *szPassword, char *szMode,

				  char *szFileFrom, char *szFileTo, char *szLogger)
{
	/* Formato de script de File-Transfer-Protocol para Tandem-Guardian */
	char   szScriptFrmt[] = "open %s\n"
							"user %s %s\n"
							"%s\n"
							"send %s %s\n"
							"close\n" ;
	/* Buffer de script de FTP */
	char   szScript[MSG_DEFAULT_LEN] = {0};
	/* Buffer de comando de FTP o NET (128 caracteres mas que el buffer de lectura, para el comando) */
	char   szCommand[MSG_DEFAULT_LEN+128] = {0};
	/* Logger */
	char	szLogFile[256] = {0};
	/* Handler para archivo temporal de scripting de FTP */
	FILE	*hTmpFile     = NULL;
	char  *pchExtension = NULL,
			   szAuxTmpFile[] = {".\\transfer.ftp"},
			  *pszTmpFile   = szAuxTmpFile;
	int    iRetValSys    = 0,
			   iRetValRemove = 0;
	/* Auxiliares para verificacion del logger de FTP */
	pvoid_t hLogFile = NULL;
	long	lSize = 0L;
  /* Tipo de dato entero retornado */
  typedef unsigned long LRESULT;

	/****************************************************
	* Ejemplo de script de FTP:
	* " open 200.200.4.4
	*   user test.super 12345678
	*   binary
	*   send c:\soat\0268\ex990101 $db24.soat0268.ex990101
	*   close "
	****************************************************/

	/****************************************************
	* Ejemplo de comando de FTP:
	* " ftp.exe -n -s:transfer.ftp > transfer.log "
	****************************************************/

	/* Precondiciones : todos punteros no nulos */
	if(!(szHost && szUser && szPassword && szMode && szFileFrom && szFileTo))
		return (-1);

	/* Formateo de script de File-Transfer-Protocol para Tandem-Guardian */
	sprintf(szScript, szScriptFrmt,
			szHost,
			szUser, szPassword,
			szMode,
			szFileFrom, szFileTo);
#if defined( _USE_TMP_FILENAME_ )
#if defined( __GNUC__ )
	/* Nombre para archivo temporal recomendado GNU LINUX*/
	pszTmpFile = mkstemp(NULL);
#else
	/* Nombre para archivo temporal */
	pszTmpFile = tmpnam(NULL);
#endif /* __GNUC__ */  
#endif /* _USE_TMP_FILENAME_ */
	if(pszTmpFile == NULL)
		return (LRESULT)FALSE;
	/* Apertura de archivo temporal */
	hTmpFile = fopen(pszTmpFile, "wt");
	if(hTmpFile == NULL)
	{
		/* Reintento de apertura de archivo temporal, ya que el nombre */
		/* generado puede ser sobre un directorio sin permisos... */
		/* Se intenta directorio actual */
		pszTmpFile = szAuxTmpFile;
		hTmpFile = fopen(pszTmpFile, "wt");
		if(hTmpFile == NULL)
			return (-2);
	};
	/* Escritura al archivo temporal */
	fprintf(hTmpFile, szScript);
	/* Flush al archivo temporal */
	fflush(hTmpFile);

	/* Se parametriza el Logger? */
	if(szLogger != NULL)
	{
		/* De entrada o de salida es este parametro? Verificar 1er. caracter */
		if(szLogger[0] != 0x00 && szLogger[0] != ' ')
			strcpy(szLogFile, szLogger);
		else
		{
			/* Asumir que es de salida y copiar el nombre adoptado para el logger */
			strcpy(szLogFile, pszTmpFile);
			strcat(szLogFile, ".log");
			strcpy(szLogger, szLogFile);
		};
	}
	else
	{
		strcpy(szLogFile, pszTmpFile);
		strcat(szLogFile, ".log");
	};
	/* Formateo de Comando FTP al Sistema Operativo */
	sprintf(szCommand, "ftp -n -s:%s > %s", pszTmpFile, szLogger);
	/* Comando al Sistema Operativo */
	iRetValSys = system(szCommand);

	/* Flush al archivo temporal */
	fflush(hTmpFile);
	/* Cerrar archivo temporal, y borrarlo por ende */
	fclose(hTmpFile);

	/* While file remains... try to delete it */
	do
		iRetValRemove = remove(pszTmpFile);
	while( errno != ENOENT && errno != EACCES && iRetValRemove != 0 );

	/* Retorno dependiente de "system()" */
	return (iRetValSys);
}

/* Used as a thread? */
#if defined( _WIN32 ) && defined( _WINDOWS )
#define PRINT_FILE_AS_THREAD
#endif
/* Print buffer size */
#define PRINTBUFFER_SIZE	4096

/* Print File function */
int PrintFile(const char *lpszFileName)
	{
#if defined( _WIN32 ) && defined( _WINDOWS )
	ULONG		  ulLen                 = 0;        /* I-O return value */
	DWORD     dwJobId               = 0;        /* JobId */
	DWORD     dwError               = 0;        /* Error Code */
	HANDLE		hPrinter              = NULL,	    /* Printer handle */
	      		hFile                 = NULL;     /* Input File handle */
	PCHAR		  pszSeparator          = NULL;     /* Comma separator */
	BOOL		  bResult               = FALSE;    /* Boolean result */
	CHAR		  szDefaultPrinter[128];            /* Default Printer,Driver,Spool */
	CHAR		  szPrinterName[128];               /* Printer Name */
	BYTE		  bBuffer[PRINTBUFFER_SIZE] ;	      /* Read-Write buffer */
	MSG			  msg;							    /* MS-Windows temporary message */
	OSVERSIONINFO osvData;          /* O.S. version data */
	int       iDocLevel            = 1;        /* Document level (1=WinNT,2=Win95) */
	union 	{									    /* Document info for Printing */
			DOC_INFO_1	diData1;      /* Document info Level-1 WinNT */
			DOC_INFO_2	diData2;			/* Document info Level-2 Win95 */
			}	  diDocInfo;

	/* Open Input File */
	hFile = CreateFile( lpszFileName             ,  /* File Name */
	                    GENERIC_READ             ,  /* Access mode */
          						FILE_SHARE_READ          ,  /* Share mode */
                      NULL                     ,  /* Secutity Attributes */
					          	OPEN_EXISTING            ,  /* Creation mode */
          						FILE_FLAG_SEQUENTIAL_SCAN,  /* File mode */
                      NULL                     ); /* Template */
	if(hFile == NULL)
		return (-1);

	/* Operating System Version data */
	osvData.dwOSVersionInfoSize = sizeof osvData;
	if(!GetVersionEx( &osvData ))
		return(-1);

	/* Default Printer Name, Driver and Spool */

	GetProfileString(   "Windows",
						"Device",
						"PRN",
						szDefaultPrinter,
						sizeof szDefaultPrinter );
    /* String is "Printer-Name,Device-Name,Spool-Name" */
	if((pszSeparator = strchr( szDefaultPrinter, ',')) == NULL)
		return (-1);
	/* Extract printer name, terminating with zero */
	strncpy( szPrinterName, szDefaultPrinter, pszSeparator - szDefaultPrinter );
	szPrinterName[pszSeparator - szDefaultPrinter] = 0x00;

	/* Open Printer */
	bResult = OpenPrinter( szPrinterName, &hPrinter, NULL);
	if(!bResult)
		{
		dwError = GetLastError();
		return (int)dwError;
		}

	/* Segun Sistema Operativo corriendo... */
	if( osvData.dwPlatformId == VER_PLATFORM_WIN32_NT ) /* Windows NT */
		{
		/* Document properties */
		iDocLevel = 1;
		diDocInfo.diData1.pDocName    = (LPTSTR)lpszFileName;
		diDocInfo.diData1.pOutputFile = NULL;
		diDocInfo.diData1.pDatatype   = NULL;
		}
	else if( osvData.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) /* Windows 95 */
		{
		/* Document properties */
		iDocLevel = 2;
		diDocInfo.diData2.pDocName    = (LPTSTR)lpszFileName;
		diDocInfo.diData2.pOutputFile = NULL;
		diDocInfo.diData2.pDatatype   = NULL;
		diDocInfo.diData2.dwMode      = 0;
		diDocInfo.diData2.JobId		  = 0;
		}/*end-doc-level */

	/* Start Document Printing */
	dwJobId = StartDocPrinter( hPrinter, iDocLevel, (LPBYTE)&diDocInfo);
	/* Error? */
	if(dwJobId == 0)
		{
		dwError = GetLastError();
		/* Close Printer */
		bResult = ClosePrinter( hPrinter );
		return (int)dwError;
		}
	else
		bResult = StartPagePrinter( hPrinter );

	/* Write cycle */
	while( ReadFile( hFile, (LPVOID)bBuffer, sizeof bBuffer, &ulLen, NULL )
	       && (ulLen > 0)
		   && (bResult == TRUE) )
		{
		/* Write buffer */
		bResult = WritePrinter( hPrinter, bBuffer, ulLen, &ulLen);
		ulLen   = 0;
		/* Yields control to other tasks after writing... */
		while(PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ))
			{
		 	TranslateMessage( &msg );
		 	DispatchMessage( &msg );
		 	}/*if */
		}

	/* Close Input File */
	bResult = CloseHandle( hFile );
	/* End Document Printing */
	bResult = EndPagePrinter( hPrinter );
	bResult = EndDocPrinter( hPrinter );
	/* Close Printer */
	bResult = ClosePrinter( hPrinter );

#ifdef PRINT_FILE_AS_THREAD
	/* Return exit code */
	ExitThread( (bResult == FALSE) ? (-1) : 0 );
	/* Return result (to avoid compiler warnings) */
	return ( (bResult == FALSE) ? (-1) : 0 );
#else
	/* Return result */
	return ( (bResult == FALSE) ? (-1) : 0 );
#endif /* endif-post-printing */

#else
	/* Return error, not yet implemented */
	return (-1);
#endif /* endif-win32 */
	}

/* Manejo de Impresion de Archivos */
boolean_t DoFilePrinting(LPSTR lpszFileName)
{
#ifdef PRINT_FILE_AS_THREAD
	/* Print file a thread... */
	HANDLE  hThread    = NULL;   /* Thread handle */
	DWORD   dwThreadId = 0;	     /* Thread Id */
	DWORD   dwRetVal   = 0;      /* Thread Return Value */

	/* Create the thread, but don磘 start it... */
	hThread = CreateThread( NULL ,  /* Security Attributes */
		  0 ,  /* Stack size */
      (LPTHREAD_START_ROUTINE)PrintFile,  /* Routine */
			(LPVOID)(LPSTR)lpszFileName ,  /* Parameter */
		   CREATE_SUSPENDED ,  /* Creation Flags */
			&dwThreadId ); /* Thread Id */
	if( hThread == NULL)

		return FALSE;
	/* Start the thread */
	if(ResumeThread( hThread ) == (-1L))
		return FALSE;
	/* Wait a few miliseconds... */
	Sleep( 100L );
	/* Get Exit Code */
	if(!GetExitCodeThread( hThread, &dwRetVal))
		return FALSE;
	/* Return Value */
	return ( dwRetVal == 0 || dwRetVal == STILL_ACTIVE)
		? TRUE
		: FALSE;
#else
	/* Return Value */
	return ( PrintFile(lpszFileName) == 0 )
			? TRUE
			: FALSE;
#endif /*end-if-post-printing-as-thread */
}/*end-DoFilePrinting */


/************************************************************************
* Funcion utilitaria que retorna la cantidad de bytes numericos en string
************************************************************************/
short EXPORT_ATTR  strnumlen( char *pszValue , const short nMax )
{
	short iLen = 0;
	/* Mientras haya caracteres numericos, contar digitos, hasta un tope maximo */
	for( iLen = 0;
		pszValue != NULL && *pszValue >= '0' && *pszValue <= '9' && iLen < nMax ;
		iLen++ , pszValue++ )
			;
	/* Retornar la longitud hallada */
	return iLen;
}

/************************************************************************
* Funcion utilitaria que retorna la cantidad de bytes numericos en string
************************************************************************/
short EXPORT_ATTR  strnumlenpad( char *pszValue , const short nMax , char chPadding)
{
	short     iLen = 0;
	boolean_t bPadding = is_false;
	/* Mientras haya caracteres numericos, contar digitos, hasta un tope maximo */
	for( iLen = 0;
		pszValue != NULL &&
			((*pszValue >= '0' && *pszValue <= '9') || *pszValue == chPadding) &&
			iLen < nMax ;
		iLen++ , pszValue++ )
		{
			/* Se encontro el caracter de padding (gralmente. es un blanco) ? */
			if(*pszValue == chPadding)
			{
				/* Establecer inicio de padding, que no debe estar "roto" luego */
				bPadding = is_true;
				continue;
			}
			/* Numericos despues de un padding ? Error */
			if(*pszValue >= '0' && *pszValue <= '9' && is_true == bPadding )
				/* Terminar conteo */
				break;
		}
	/* Retornar la longitud hallada */
	return iLen;
}
/************************************************************************/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -