20140629:简单的打印函数执行日志的函数代码WriteLog函数(适用于c++builder等,未加载lib文件)

时间:2022-10-04 20:29:11
#include<windows.h>
#include<FSTREAM>
#include<stdio.h>
#include<tchar.h>
#include<process.h>
using namespace std;
char pLogPath[1000];
char pCurrentDirectory[1000];

int WriteLog(const char *format, ... );
bool MakeGlobalPath();
bool execwait(char *cmdline,char *cmd,int timeout);

 int WriteLog(const char *format, ... )  //if succeeds,return 0.else return 1.
{    
    MakeGlobalPath();
    strcat(pLogPath,"SQLSelect.txt");      
    FILE    *fStream = fopen(pLogPath,"a+");    
    if (fStream != NULL)    
    {       
        try{
            va_list  ap;    
            TCHAR    strTemp[5120];    
            va_start(ap,format);    
            vsprintf(strTemp,format,ap);    
            fprintf(fStream,"%s\n",strTemp);
            va_end(ap);    
        }    
        catch (...)    
        {    
        }    
        fclose(fStream);    
        fStream = NULL;    
        return 0;    
    }    
    else    
    {    
        return 1;    
    }    
    
}    

bool MakeGlobalPath()
{      
    char    lpModuleFilePath[1000];      
    DWORD   dwModuleFilePath = 0;
    DWORD   iIndex = 0;      
    DWORD   iPosition = 0;      
    

    memset(lpModuleFilePath,0,sizeof(char)*1000);      
    memset(pCurrentDirectory,0,sizeof(char)*1000);      
    
    
    dwModuleFilePath = GetModuleFileName(NULL,lpModuleFilePath,1000);  //get the exe program's full path name    

    
    for (;iIndex<dwModuleFilePath;iIndex++)      
    {      
        if (lpModuleFilePath[iIndex]=='\\')      
        {      
            iPosition = iIndex;                                         //get the last blackslash    
        }       
    }
    strncpy(pCurrentDirectory,lpModuleFilePath,iPosition+1);      
    pCurrentDirectory[iPosition+1] = '\0';                              //null    
    strcpy(pLogPath,pCurrentDirectory);      
    
    
    //cout<<"pCurrentDirectory"<<pCurrentDirectory<<endl<<"pLogPath"<<pLogPath<<endl;
    
    return true;      
}

 
bool execwait(char *cmdline,char *cmd,int timeout)  
{  
    PROCESS_INFORMATION   pi;  
    STARTUPINFO si;  
    ZeroMemory( &pi, sizeof(pi) );  
    ZeroMemory( &si, sizeof(si) );  
  
    si.cb = sizeof(si);  
    si.dwFlags   =   STARTF_USESHOWWINDOW;   
    si.wShowWindow   =   SW_HIDE;  
    CreateProcess(cmdline,cmd,NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);  
    WaitForSingleObject(pi.hProcess ,timeout);  
    //Edit1->Text = "ddd";  
    CloseHandle( pi.hProcess );  
    CloseHandle( pi.hThread );  
    return true;  
}