快速获取文件的行数

来源:互联网 发布:淘宝比较好的银饰店 编辑:程序博客网 时间:2024/04/29 18:41

目的是快速的获取文件的行数,不能用不断的读文本的方式,否则内存消耗和时间消耗都无法容忍。

解决方案是调用Linux 的 wc命令。 获取行数用的是 -l , 其实可以获取总的字节数 -c , 最大行的长度-L, 这些随后可以替换。




#include <stdio.h>   #include <string.h>int cover(char *str){    int index = strchr((const char*)str, ' ') - str;    str[index] = '\0';    return atoi(str);}int getFileAttr(const char *fileName, char C, char *buff){    FILE *fstream=NULL;     sprintf(buff, "wc -%c %s", C, fileName);    if(fstream=popen(buff,"r"))    {        memset(buff, 0x00, sizeof(buff));        if(fgets(buff, sizeof(buff), fstream))        {            pclose(fstream);            return cover(buff);        }    }    if(fstream)        pclose(fstream);    return -1;}int main(int argc,char*argv[]){       char buff[256] = {0};    printf("res:%d\n", getFileAttr("dic.txt", 'c', buff));    return 0;    }  



0 0