红联Linux门户
Linux帮助

查找文件中是否有 匹配内容

发布时间:2010-11-08 11:03:29来源:红联作者:zzm35837995
用C写程序 , 功能是 :在一个文件(例如 test.conf )中 ,想知道 里面有没有 要查找的字符,数字。。。。(例如“hello,welcome !”12345) ,有就返回yes ,没有返回no ,该如何实现呢?
文章评论

共有 1 条评论

  1. 考乌特莫克 于 2011-01-08 02:45:56发表:

    写了个程序实现上面的描述,本想法一下测试结果的但是不能发本地图片,包括包含和不包含的情形都是可以检测到的。大家可以自己编译运行一下:

    #include
    #include
    #include

    #define MAX_BUFFER_LEN 128
    typedef unsigned char UCHAR;
    typedef unsigned long ULONG;

    UCHAR *g_szPath = "./test.conf";
    UCHAR *g_szStr = "hello world!";
    UCHAR aucTMP[MAX_BUFFER_LEN] = {0};
    ULONG g_ulCurLen = 0;

    void init_oper()
    {
    memset(aucTMP, 0, MAX_BUFFER_LEN);
    g_ulCurLen = 0;

    return;
    }

    int main_oper(UCHAR ucWord)
    {
    ULONG ulRet = 0;
    ULONG ulPos = g_ulCurLen;

    if (g_szStr[ulPos] == ucWord)
    {
    aucTMP[g_ulCurLen++] = ucWord;
    }
    else
    {
    init_oper();
    }

    if (g_ulCurLen == strlen(g_szStr))
    {
    ulRet = 1;
    }

    return ulRet;
    }

    int main()
    {
    FILE *fp = NULL;
    UCHAR *pucBuffer = NULL;
    ULONG ulLen = 0;

    int iRet = 0;
    ULONG i = 0;

    fp = fopen(g_szPath, "r");
    if (NULL == fp)
    {
    printf("open file [%s] failed!\n", g_szPath);
    return -1;
    }

    /*将文件中的锚标记移动到文件尾*/
    fseek(fp, 0, SEEK_END);
    /*获取文件长度*/
    ulLen = ftell(fp) + 1;

    pucBuffer = (char *)malloc(ulLen * sizeof(char));
    if (NULL == pucBuffer)
    {
    fclose(fp);
    printf("malloc len = [%d] failed!\n", ulLen);
    return -1;
    }

    rewind(fp);
    if (fgets(pucBuffer, ulLen, fp) == NULL)
    {
    fclose(fp);
    free(pucBuffer);
    printf("fgets failed!\n");
    return -1;
    }
    fclose(fp);

    init_oper();
    while(i < ulLen)
    {
    if (0 == pucBuffer[i])
    {
    break;
    }

    iRet = main_oper(pucBuffer[i]);
    if (iRet > 0)
    {
    break;
    }
    i++;
    }
    free(pucBuffer);

    if (iRet > 0)
    {
    printf("YES\n");
    }
    else
    {
    printf("NO\n");
    }

    return 0;
    }