如何用c语言高效的读取一个很大的txt数据文件

如何用c语言高效的读取一个很大的txt数据文件,第1张

#include <stdio.h>

#include <string.h>

#define MAXSIZE 4000000

struct password {

char psw[12]// 密码名称

int counter // 出现次数计数器

}

int Append(struct password a[], int *n, char psw[]) {

int i

for(i = 0i <*n++i) {

if(strcmp(a[i].psw,psw) == 0) {

++a[i].counter

return 2

}

}

if(*n <MAXSIZE) {

strcpy(a[*n].psw,psw)

a[*n].counter = 1

++(*n)

return 1

}

return 0

}

int main() {

struct password a[MAXSIZE]

char psw[12]

int i,n = 0,id

char infilename[] = "indata.txt"

char outfilename[] = "outdata.txt"

FILE *inf,*outf

if((inf = fopen(infilename,"rt")) == NULL) {

printf("不能打开数据文件:%s。\n",infilename)

return 1

}

while(fscanf(inf,"%d %11s",&id,psw) == 2) {

if(Append(a,&n,psw) == 0) break

}

fclose(inf)

if((outf = fopen(outfilename,"wt")) == NULL) {

printf("不能打开数据文件:%s。\n",outfilename)

return 2

}

for(i = 0i <n++i)

fprintf(outf,"%s %d\n",a[i].psw,a[i].counter)

fclose(outf)

return 0

}

估计可能是数组越界,修改如下:

int Append(struct password a[], int *n, char psw[]) {

int i

for(i = 0i <*n &&i <MAXSIZE++i) {

if(strcmp(a[i].psw,psw) == 0) {

++a[i].counter

return 2

}

}

if(*n <MAXSIZE) {

strcpy(a[*n].psw,psw)

a[*n].counter = 1

++(*n)

return 1

}

return 0

}

intfile_size(char*filename)

{

FILE*fp=fopen(filename,"r")

if(!fp)return-1

fseek(fp,0L,SEEK_END)

intsize=ftell(fp)

fclose(fp)

returnsize

}

扩展资料

C语言获取文件长度及全部内容

FILE*fp

fp=fopen("localfile","rb")//localfile文件名

fseek(fp,0L,SEEK_END)/*定位到文件末尾*/

flen=ftell(fp)/*得到文件大小*/

p=(char*)malloc(flen+1)/*根据文件大小动态分配内存空间*/

if(p==NULL)

{

fclose(fp)

return0

}

fseek(fp,0L,SEEK_SET)/*定位到文件开头*/

fread(p,flen,1,fp)/*一次性读取全部文件内容*/

p[flen]=0/*字符串结束标志*/


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/6039821.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-12
下一篇 2023-03-12

发表评论

登录后才能评论

评论列表(0条)

保存