大佬教程收集整理的这篇文章主要介绍了如何解析不能完全适合内存RAM的文件,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我的框架:
#include <stdio.h> #include <stdlib.h> #include <String.h> #include <time.h> int Parse(const char *filename,const char *outputfilE); int main(void) { clock_t t1 = clock(); /* ............................................................................................................................. */ Parse("file.txt",null); /* ............................................................................................................................. */ clock_t t2 = clock(); fprintf(stderr,"time elapsed: %.4f\n",(doublE)(t2 - t1) / CLOCKS_PER_SEC); fprintf(stderr,"Press any key to conTinue . . . "); getchar(); return 0; } long GetFileSize(FILE * fp) { long f_size; fseek(fp,0L,SEEK_END); f_size = ftell(fp); fseek(fp,SEEK_SET); return f_size; } char *dump_file_to_array(FILE *fp,size_t f_sizE) { char *buf = (char *)calloc(f_size + 1,1); if (buf) { size_t n = 0; while (fgets(buf + n,INT_MAX,fp)) { n += strlen(buf + n); } } return buf; } int Parse(const char *filename,const char *outputfilE) { /* open file for reading in text mode */ FILE *fp = fopen(filename,"r"); if (!fp) { perror(fileName); return 1; } /* store file in dynamic memory and close file */ size_t f_size = GetFileSize(fp); char *buf = dump_file_to_array(fp,f_sizE); fclose(fp); if (!buf) { fputs("error: memory alLOCATIOn Failed.\n",stderr); return 2; } /* state machine variables */ // ........ /* array index variables */ size_t x = 0; size_t y = 0; /* main loop */ while (buf[x]) { switch (buf[x]) { /* ... */ } x++; } /* NUL-terminate array at y */ buf[y] = '\0'; /* write buffer to file and clean up */ outputfile ? fp = fopen(outputfile,"w") : fp = fopen(filename,"w"); if (!fp) { outputfile ? perror(outputfilE) : perror(fileName); } else { fputs(buf,fp); fclose(fp); } free(buf); return 0; }
int delete_pattern_in_file(const char *filename,const char *pattern,"r"); if (!fp) { perror(fileName); return 1; } /* copy file contents to buffer and close file */ size_t f_size = GetFileSize(fp); char *buf = dump_file_to_array(fp,f_sizE); fclose(fp); if (!buf) { fputs("error - memory alLOCATIOn Failed",stderr); return 2; } /* delete first match */ size_t n = 0,pattern_len = strlen(pattern); char *tmp,*ptr = strstr(buf,pattern); if (!ptr) { fputs("No match found.\n",stderr); free(buf); return -1; } else { n = ptr - buf; ptr += pattern_len; tmp = ptr; } /* delete the rest */ while (ptr = strstr(ptr,pattern)) { while (tmp < ptr) { buf[n++] = *tmp++; } ptr += pattern_len; tmp = ptr; } /* copy the rest of the buffer */ strcpy(buf + n,tmp); /* open file for wriTing and print the processed buffer to it */ outputfile ? fp = fopen(outputfile,fp); fclose(fp); } free(buf); return 0; }
以上是大佬教程为你收集整理的如何解析不能完全适合内存RAM的文件全部内容,希望文章能够帮你解决如何解析不能完全适合内存RAM的文件所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。