返回顶部

收藏

逐行搜索目录中的文件内容并输出到Excel

更多

逐行搜索目录中的文件内容并输出到Excel

[C/C++]代码

HRESULT AnsiToUnicode(LPCSTR pszA, LPOLESTR* ppszW)
{

    ULONG cCharacters;
    DWORD dwError;

    // If input is null then just return the same.
    if (NULL == pszA)
    {
        *ppszW = NULL;
        return NOERROR;
    }

    // Determine number of wide characters to be allocated for the
    // Unicode string.
    cCharacters = strlen(pszA)+1;

    // Use of the OLE allocator is required if the resultant Unicode
    // string will be passed to another COM component and if that
    // component will free it. Otherwise you can use your own allocator.
    *ppszW = (LPOLESTR) CoTaskMemAlloc(cCharacters*2);
    if (NULL == *ppszW)
        return E_OUTOFMEMORY;

    // Covert to Unicode.
    if (0 == MultiByteToWideChar(CP_ACP, 0, pszA, cCharacters,
        *ppszW, cCharacters))
    {
        dwError = GetLastError();
        CoTaskMemFree(*ppszW);
        *ppszW = NULL;
        return HRESULT_FROM_WIN32(dwError);
    }

    return NOERROR;
}
bool Exists(string fileName) {
    struct _stat buf;
    return _stat(fileName.c_str(), &buf) == 0;
}
long counter=0;
struct _finddata_t finddata;      /* _findfirst, filenext block */ 
                                  /* This function prints out all lines containing a substring.  There are some   
                                  * conditions that may be passed to the function.                    
                                  *     
                                  * RETURN: If the string was found at least once, returns 1.         
                                  * If the string was not found at all, returns 0.                    
*/    
int find_str (BasicExcelWorksheet* sheet,char *sz, FILE *p, int invert_search,                      
              int count_lines, int number_output, int ignore_case, int at_start, int literal_search,    
              int at_end, int reg_express, int exact_match, int sub_dirs, int only_fname)     
{      
    int i, length;  
    long line_number = 0, total_lines = 0;  
    char *c, temp_str[MAX_STR], this_line[MAX_STR];                    

    /* Convert to upper if needed */    
    if (ignore_case)
    {  
        length = strlen (sz); 
        for (i = 0; i < length; i++)    
            sz[i] = toupper (sz[i]);
    }  

    /* Scan the file until EOF */  
    while (fgets (temp_str, MAX_STR, p) != NULL)
    {  
        /* Remove the trailing newline */   
        length = strlen (temp_str);
        if (temp_str[length-1] == '\n')
            temp_str[length-1] = '\0';

        /* Increment number of lines */ 
        line_number++;        
        strcpy (this_line, temp_str);   

        /* Convert to upper if needed */
        if (ignore_case)      
        {  
            for (i = 0; i < length; i++)  
                temp_str[i] = toupper (temp_str[i]);
        }  

        /* Locate the substring */ 

        /* strstr() returns a pointer to the first occurrence in the   
        string of the substring */
        c = strstr (temp_str, sz); 

        if ( ((invert_search) ? (c == NULL) : (c != NULL)) )           
        {  
            if (!count_lines)     
            {         
                if (number_output)
                {
                    //printf ("%ld:", line_number); 
                    sheet->Cell(counter,0)->SetInteger(line_number);
                }
                LPCSTR lstr=finddata.name;
                LPOLESTR ppszW;
                AnsiToUnicode(lstr,&ppszW);
                /* Print the line of text */
                sheet->Cell(counter,1)->SetWString(ppszW);
                LPCSTR line=finddata.name;
                LPOLESTR ppszWline;
                AnsiToUnicode(line,&ppszWline);
                //puts (this_line); 
                sheet->Cell(counter++,2)->SetWString(ppszWline);
            }         

            total_lines++;        
        } /* long if */         
    } /* while fgets */     

    if (count_lines)
        /* Just show num. lines that contain the string */             
        printf ("%ld\n", total_lines);

        /* RETURN: If the string was found at least once, returns 1.        
        * If the string was not found at all, returns 0.                   
    */   
    return (total_lines > 0 ? 1 : 0);   
}      

/* Main program */
void main (int argc, char **argv)
{      
    char *opt, *needle = NULL;
    int ret = 0;    

    int invert_search = 0;        /* flag to invert the search */      
    int count_lines = 0;          /* flag to whether/not count lines */
    int number_output = 0;        /* flag to print line numbers */     
    int ignore_case = 0;          /* flag to be case insensitive */    
    int at_start = 0;             /* flag to Match if at the beginning of a line. */        
    int at_end = 0;               /* flag to Match if at the beginning of a line. */        
    int reg_express = 0;         /* flag to use/not use regular expressions */    
    int exact_match = 0;          /* flag to be exact match */         
    int sub_dirs= 0;              /* this and all subdirectories */    
    int only_fname= 0;            /* print only the name of the file*/ 
    int literal_search=0;     

    FILE *pfile;              /* file pointer */
    int hfind;                /* search handle */                      
    /* Scan the command line */    
    while ((--argc) && (needle == NULL))
    {  
        if (*(opt = *++argv) == '/')    
        {         
            switch (opt[1])   
            {         
            case 'b':         
            case 'B':     /* Matches pattern if at the beginning of a line */     
                at_start = 1;   
                break;

                //case 'c':       
                //case 'C':       /* Literal? */
                //  literal_search = 1;
                //  break;        

            case 'e':         
            case 'E':     /* matches pattern if at end of line */      
                at_end = 1;     
                break;

            case 'i':         
            case 'I':     /* Ignore */  
                ignore_case = 1;
                break;

            case 'm':         
            case 'M':     /* only filename */
                only_fname = 1; 
                break;

            case 'n':         
            case 'N':     /* Number */  
                number_output = 1;   
                break;

            case 'r':         
            case 'R':     /* search strings as regular expressions */  
                reg_express = 1;
                break;

            case 's':         
            case 'S':     /* search files in child directory too*/     
                sub_dirs = 1;   
                break;

            case 'v':         
            case 'V':     /* Not with */
                invert_search = 1;   
                break;

            case 'x':         
            case 'X':     /* exact match */ 
                exact_match = 1;
                break;

            default:   
                exit (2);       /* syntax error .. return error 2 */     
                break;
            }         
        }         
        else        
        {         
            /* Get the string */   
            if (needle == NULL)   
            {         
                /* Assign the string to find */ 
                needle = *argv;    
            }         
        }  
    }  

    /* Check for search string */  
    if (needle == NULL)       
    {  
        /* No string? */   
        exit (1);   
    }  

    BasicExcel e;
    // create a workbook
    e.New();
    // create a sheet
    BasicExcelWorksheet* sheet = e.AddWorksheet(needle);
    sheet->Cell(0,0)->SetWString(L"行号");
    sheet->Cell(0,1)->SetWString(L"文件名");
    sheet->Cell(0,2)->SetWString(L"文件内容");

    /* Scan the files for the string */ 
    if (argc == 0)  
    {  
        ret = find_str (sheet,needle, stdin, invert_search, count_lines,     
            number_output, ignore_case, at_start, literal_search, at_end, reg_express, exact_match,                      
            sub_dirs, only_fname);  
    }  

    while (--argc >= 0)       
    {  
        hfind = _findfirst (*++argv, &finddata);
        if (hfind < 0)        
        {  
        /* We were not able to find a file. Display a message and      
            set the exit status. */    
            fprintf (stderr, "No such file!", *argv);//
        }  
        else        
        {         
            /* repeat find next file to match the filemask */          
            do          
            {     
                /* We have found a file, so try to open it */          
                if ((pfile = fopen (finddata.name, "r")) != NULL)          
                {     
                    //printf ("---------------- %s\n", finddata.name);       
                    ret = find_str (sheet,needle, pfile, invert_search, count_lines,        
                        number_output, ignore_case, at_start, literal_search, at_end, reg_express, exact_match,                      
                        sub_dirs, only_fname);  
                    fclose (pfile);    
                }     
                else    
                {     
                    fprintf (stderr, "Cannot open the file %s!", 
                        finddata.name);    
                } 
            }         
            while (_findnext(hfind, &finddata) > 0);                   
        }         
        _findclose(hfind);    
    } /* for each argv */   

      /* RETURN: If the string was found at least once, returns 0.        
      * If the string was not found at all, returns 1.                   
      * (Note that find_str.c returns the exact opposite values.)        
    */   
    TCHAR xlsname[] = "FindStr";
    TCHAR xlsfile[FILENAME_MAX];
    sprintf(xlsfile, "%s.xls", xlsname);    
    if(Exists(xlsfile))
    {
        int num = 2;
        while(Exists(xlsfile))
            sprintf(xlsfile, "%s%d.xls", xlsname, num++);       
    }
    e.SaveAs(xlsfile);
    exit ( (ret ? 0 : 1) );   
}

标签:c++

收藏

1人收藏

支持

0

反对

0

»更多 您可能感兴趣的代码
  1. 2017-07-23 12:42:20奇数魔方阵 by Kevin.
  2. 2017-07-18 14:15:24两种方法计算“算术表达式” by aiheng1988
  3. 2015-09-09 16:29:06将jpg转换为bmp格式的文件 by qqmmcc
  4. 2015-09-09 09:29:49可执行文件加密 by walker30
  5. 2015-09-08 18:42:46TCP端口占用查询 by 灵剑子
  6. 2015-09-08 14:16:34Luffar schack五子棋 by 蟋蟀哥
  7. 2015-09-08 10:39:34wav转mp3的程序 by 灵剑子
  8. 2015-09-03 20:10:15LZW+AES+Base64编码解码剪贴板文本 by 童学芬
  9. 2015-09-01 17:47:21猫里奥 by aiheng1988
  10. 2015-08-31 15:33:59模拟键盘操作发送字符串 by 千万不要郁闷
  11. 2018-03-30 21:56:50java自动识别用户上传的文本文件编码 by Hugh

发表评论